Must Watch!
Bash Scripting Tutorial Basic Linux command line tutorial ♦LINUX Tutorial


MustWatch

LINUX Tutorial Run Linux GUI apps on the Windows Subsystem for Linux Bochs Emulator Linux 环境变量总结 DIY: Build a Custom Minimal Linux Distribution from Source “我花了 5 年时间编写自己的操作系统!” light weight BionicPup 32 Linux distros Linux 系统结构详解 An Introduction to the Linux Linux Terminal Introduction


#!

"#!" is an operator called shebang which directs the script to the interpreter location. So, if we use"#! /bin/sh" the script gets directed to the bourne-shell. Shell Script in Linux/Unix Unix - Getting Started Basic Linux Man Linux

How to install software on Linux Mint
Choose The Best Linux Distro List of Linux distributions
Linux Terminal on Windows Bash commands KBOX — a miniature Linux Convert Android to Linux
Basic4Android building Android apps
15 Linux Terminal Commands
linux command line
Create a Live Ubuntu USB Drive With Persistent Storage

ubuntu KeyboardShortcuts

ubuntu KeyboardShortcuts ubuntu键盘快捷键

10 Command-line Tools For Data Analysis In Linux
Important Linux Commands
Introduction To The Linux Boot And Startup Processes
♦Useful Shell Commands For Data Science
Linux爱好者
ln 命令教程
给初学者的 type 命令教程
10 个增加 UNIX/Linux Shell 脚本趣味的工具
Linux 启动过程分析
为初学者准备的 ln 命令教程(5 个示例)

给初学者的 type 命令教程
升级到 Ubuntu 18.04 LTS 的理由,大波新特性到来
如何在 Linux 上安装应用程序
things-to-do-after-installing-linux-mint
best-things-installing-linux-mint

Important Linux Commands

SuSE Linux User Guide Chapter 24. Working with the Shell This section gives insight into the most important commands of your SuSE Linux system. Along with the individual commands, parameters are listed and, where appropriate, a typical sample application is introduced. To learn more about the various commands, it is usually possible to get additional information with the man program followed by the name of the command, for example, man ls. In these manual pages, move up and down with PgUp and PgDn and move between the beginning and the end of a document with Home and End. End this viewing mode by pressing Q. Learn more about the man command itself with man. There are many more commands than listed in this chapter. For information about other commands or more detailed information, we recommend the O'Reilly publication Linux in a Nutshell. In the following overview, the individual command elements are written in different typefaces. Adjust possible specifications to your needs. It makes no sense to write ls file(s), if no file named file(s) actually exists. You can usually combine several parameters, for example, by writing ls -la instead of ls -l -a.

File Commands

File Administration Commands

ls [option(s)] [file(s)] If you run ls without any additional parameters, the program will list the contents of the current directory in short form.
-l detailed list
-a displays hidden files
cp [option(s)] sourcefile targetfile Copies sourcefile to targetfile.
-i Waits for confirmation, if necessary, before an existing targetfile is overwritten
-r Copies recursively (includes subdirectories)
mv [option(s)] sourcefile targetfile Copies sourcefile to targetfile then deletes the original sourcefile.
-b Creates a backup copy of the sourcefile before moving
-i Waits for confirmation, if necessary, before an existing targetfile is overwritten
rm [option(s)] file(s) Removes the specified files from the file system. Directories are not removed by rm unless the option -r is used.
-r Deletes any existing subdirectories
-i Waits for confirmation before deleting each file.
ln [option(s)] sourcefile targetfile Creates an internal link from the sourcefile to the targetfile, under a different name. Normally, such a link points directly to the sourcefile on one and the same file system. However, if ln is executed with the -s option, it creates a symbolic link that only points to the directory where the sourcefile is located, thus enabling linking across file systems.
-s Creates a symbolic link
cd [options(s)] [directory] Changes the current directory. cd without any parameters changes to the user's home directory.
mkdir [option(s)] directoryname Creates a new directory.
rmdir [option(s)] directoryname Deletes the specified directory, provided it is already empty.
chown [option(s)] username.group file(s) Transfers the ownership of a file to the user with the specified user name.
-R Changes files and directories in all subdirectories.
chgrp [option(s)] groupname file(s) Transfers the group ownership of a given file to the group with the specified group name. The file owner can only change group ownership if a member of both the existing and the new group.
chmod [options] mode file(s) Changes the access permissions. The mode parameter has three parts: group, access, and access type. group accepts the following characters:
u user
g group
o others
For access, access is granted by the + symbol and denied by the - symbol. The access type is controlled by the following options:
r read
w write
x eXecute — executing files or changing to the directory.
s Set uid bit — the application or program is started as if it were started by the owner of the file.
gzip [parameters] file(s) This program compresses the contents of files, using complex mathematical algorithms. Files compressed in this way are given the extension .gz and need to be uncompressed before they can be used. To compress several files or even entire directories, use the tar command.
-d decompresses the packed gzip files so they return to their original size and can be processed normally (like the command gunzip).
tar options archive file(s) The tar puts one file or (usually) several files into an archive. Compression is optional. tar is a quite complex command with a number of options available. The most frequently used options are:
-f Writes the output to a file and not to the screen as is usually the case
-c Creates a new tar archive
-r Adds files to an existing archive
-t Outputs the contents of an archive
-u Adds files, but only if they are newer than the files already contained in the archive
-x Unpacks files from an archive (extraction)
-z Packs the resulting archive with gzip
-j Compresses the resulting archive with bzip2
-v Lists files processed
The archive files created by tar end with .tar. If the tar archive was also compressed using gzip, the ending is .tgz or .tar.gz. If it was compressed using bzip2, .tar.bz2. Application examples can be found in Section “Archives and Data Compression”.
locate pattern(s) The locate command can find in which directory a specified file is located. If desired, use wild cards to specify file names. The program is very speedy, as it uses a database specifically created for the purpose (rather than searching through the entire file system). This very fact, however, also results in a major drawback: locate is unable to find any files created after the latest update of its database. The database can be generated by root with updatedb.
updatedb [options(s)] This command performs an update of the database used by locate. To include files in all existing directories, run the program as root. It also makes sense to place it in the background by appending an ampersand (&), so you can immediately continue working on the same command line (updatedb &).
find [option(s)] The find command allows you to search for a file in a given directory. The first argument specifies the directory in which to start the search. The option -name must be followed by a search string, which may also include wild cards. Unlike locate, which uses a database, find scans the actual directory.

Commands to Access File Contents Commands

cat [option(s)] file(s) The cat command displays the contents of a file, printing the entire contents to the screen without interruption.
-n Numbers the output on the left margin
less [option(s)] file(s) This command can be used to browse the contents of the specified file. Scroll half a screen page up or down with PgUp and PgDn or a full screen page down with Space. Jump to the beginning or end of a file using Home and End. Press Q to exit the program.
grep [option(s)] searchstring filenames The grep command finds a specific searchstring in the specified file(s). If the search string is found, the command displays the line in which the searchstring was found along with the file name.
-i Ignores case
-l Only displays the names of the respective files, but not the text lines
-n Additionally displays the numbers of the lines in which it found a hit
-l Only lists the files in which searchstring does not occur
diff [option(s)] file1 file2 The diff command compares the contents of any two files. The output produced by the program lists all lines that do not match. This is frequently used by programmers who need only send their program alterations and not the entire source code.
-q Only reports whether the two given files differ

File Systems Commands

mount [option(s)] [<device>] mountpoint This command can be used to mount any data media, such as hard disks, CD-ROM drives, and other drives, to a directory of the Linux file system.
-r mount read-only
-t filesystem Specifies the file system. The most common are ext2 for Linux hard disks, msdos for MS-DOS media, vfat for the Windows file system, and iso9660 for CDs.
For hard disks not defined in the file /etc/fstab, the device type must also be specified. In this case, only root can mount. If the file system should also be mounted by other users, enter the option user in the appropriate line in the /etc/fstab file (separated by commas) and save this change. Further information is available in mount.
umount [option(s)] mountpoint This command unmounts a mounted drive from the file system. To prevent data loss, run this command before taking a removable data medium from its drive. Normally, only root is allowed to run the commands mount and umount. To enable other users to run these commands, edit the /etc/fstab file to specify the option user for the respective drive.

System Commands

System Information Commands

df [option(s)] [directory] The df (disk free) command, when used without any options, displays information about the total disk space, the disk space currently in use, and the free space on all the mounted drives. If a directory is specified, the information is limited to the drive on which that directory is located.
-H shows the number of occupied blocks in gigabytes, megabytes, or kilobytes — in human-readable format
-t Type of file system (ext2, nfs, etc.)
du [option(s)] [path] This command, when executed without any parameters, shows the total disk space occupied by files and subdirectories in the current directory.
-a Displays the size of each individual file
-h Output in human-readable form
-s Displays only the calculated total size
free [option(s)] The command free displays information about RAM and swap space usage, showing the total and the used amount in both categories.
-b Output in bytes
-k Output in kilobytes
-m Output in megabytes
date [option(s)] This simple program displays the current system time. If run as root, it can also be used to change the system time. Details about the program are available in date.

Processes Commands

top [options(s)] top provides a quick overview of the currently running processes. Press H to access a page that briefly explains the main options to customize the program.
ps [option(s)] [process ID] If run without any options, this command displays a table of all your own programs or processes — those you started. The options for this command are not preceded by hyphen.
aux Displays a detailed list of all processes, independent of the owner.
kill [option(s)] process ID Unfortunately, sometimes a program cannot be terminated in the normal way. However, in most cases, you should still be able to stop such a runaway program by executing the kill command, specifying the respective process ID (see top and ps). kill sends a TERM signal that instructs the program to shut itself down. If this does not help, the following parameter can be used:
-9 Sends a KILL signal instead of a TERM signal, with which the process really is annihilated by the operating system. This brings the specific processes to an end in almost all cases.
killall [option(s)] processname This command is similar to kill, but uses the process name (instead of the process ID) as an argument, causing all processes with that name to be killed.

Network Commands

ping [option(s)] host name|IP address The ping command is the standard tool for testing the basic functionality of TCP/IP networks. It sends a small data packet to the destination host, requesting an immediate reply. If this works, ping displays a message to that effect, which indicates that the network link is basically functioning.
-c number Determines the total number of packages to send and ends after they have been dispatched. By default, there is no limitation set.
-f flood ping: sends as many data packages as possible. A popular means, reserved to root, to test networks.
-i value Specifies the interval between two data packages in seconds. Default: one second
nslookup The Domain Name System resolves domain names to IP addresses. With this tool, send queries to information servers (DNS servers).
telnet [option(s)] host name or IP address Telnet is actually an Internet protocol that enables you to work on remote hosts across a network. telnet is also the name of a Linux program that uses this protocol to enable operations on remote computers.

Warning

Do not use telnet over a network on which third parties can eavesdrop. Particularly on the Internet, use encrypted transfer methods, such as ssh, to avoid the risk of malicious misuse of a password (see the man page for ssh).

Miscellaneous Commands

passwd [option(s)] [username] Users may change their own passwords at any time using this command. Furthermore, the administrator root can use the command to change the password of any user on the system.
su [option(s)] [username] The su command makes it possible to log in under a different user name from a running session. When using the command without specifying a user name, you will be prompted for the root password. Specify a user name and the corresponding password to use the environment of the respective user. The password is not required from root, as root is authorized to assume the identity of any user.
halt [option(s)] To avoid loss of data, you should always use this program to shut down your system.
reboot [option(s)] Does the same as halt with the difference that the system performs an immediate reboot.
clear This command cleans up the visible area of the console. It has no options.

Ubuntu vs Fedora

Ubuntu 和 Fedora 都是最流行的 Linux 发行版之一,在两者之间做出选择实非易事。 在这篇文章里,我会对比一下 Ubuntu 和 Fedora 的不同特点,帮助你进行决策。 请注意,这篇文章主要是从桌面版的角度进行对比的。 Fedora 或者 Ubuntu 针对容器的特殊版本不会被考虑在内。 Ubuntu vs Fedora: 哪一个更好? 不同 Linux 发行版之间的区别主要体现在以下几个方面: ◈基础发行版(Debian、红帽、Arch,或者是从头做起) ◈安装方式 ◈支持的桌面环境 ◈软件包管理、软件支持和更新 ◈硬件支持 ◈开发团队(由企业支持,还是由业余爱好者创建) ◈发布周期 ◈社区和线上支持 下面我们来看一下 Ubuntu 和 Fedora 之间的相似之处和不同之处。 掌握了这些信息之后,也许就更容易在两者之间做出选择了。 安装方式 Ubuntu 的 Ubiquity 安装器是最好用的安装器之一。 我认为这是让 Ubuntu 如此流行的重要原因之一,因为在 2004 年 Ubuntu 刚刚诞生的时候,安装 Linux 还是一个很庞大的工程。 Ubuntu 安装器可以让你在大约 10 分钟左右完成安装。 大多数情况下,它还可以识别出机器里安装的 Windows 系统,并且只需要几下点击就可以实现 Ubuntu 和 Windows 的双系统启动。 锦上添花的是,在安装 Ubuntu 的过程中你还可以进行系统更新,或者是安装第三方编译码器。 Ubuntu Installer Fedora 使用的是 Anaconda 安装器,拥有简单易用的界面,同样简化了安装过程。 Fedora Installer | Image Credit Fedora Magazine Fodora 还提供了一个可以在 Windows 操作系统上下载并创建 Fedora live USB 的写入工具。 不过我在大约两年前尝试使用它的时候并不成功,最后使用了一个常规的创建 live USB 的软件。 根据我的经验,安装 Ubuntu 要比安装 Fedora 容易一些。 不过这并不是说安装 Fedora 有多困难,只是 Ubuntu 更简单而已。 桌面环境 Ubuntu 和 Fedora 默认都使用 GNOME 桌面环境。 GNOME Desktop in Fedora Fedora 使用的是原装的 GNOME 桌面,而 Ubuntu 则在此基础上做了个性化调整,让它看起来就像 Ubuntu 之前使用的 Unity 桌面环境。 GNOME desktop customized by Ubuntu 除了 GNOME,Ubuntu 和 Fedora 都提供了一些其它桌面环境的版本。 Ubuntu 有 Kubuntu、Xubuntu、Lubuntu 等版本,分别提供不同的桌面环境。 虽然它们都是 Ubuntu 的官方版本,但是却不是由 Canonical 的 Ubuntu 团队直接开发的,而是由另外的团队开发。 Fedora 通过 Fedora Spins 的方式提供了一些不同桌面环境的版本。 和 Kubuntu、Lubuntu 等版本不同的是,这些版本并非由独立团队开发,而是由 Fedora 核心团队开发的。 软件包管理和可用软件数量 Ubuntu 使用 APT 软件包管理器提供软件并进行管理(包括应用程序、库,以及其它所需编解码器),而 Fedora 使用 DNF 软件包管理器。 Ubuntu 拥有庞大的软件仓库,能够让你轻松安装数以千计的程序,包括 FOSS(LCTT 译注: Free and Open-Source Software 的缩写,自由开源软件)和非 FOSS 的软件。 Fedora 则只专注于提供开源软件。 虽然这一点在最近的版本里有所转变,但是 Fedora 的软件仓库在规模上仍然比 Ubuntu 的要逊色一些。 一些第三方软件开发者为 Linux 提供像 .exe 文件一样可以点击安装的软件包。 在 Ubuntu 里这些软件包是 .deb 格式的,在 Fedora 里是 .rpm 格式的。 大多数软件供应商都为 Linux 用户提供 DEB 和 RPM 文件,但是我也经历过供应商只提供 DEB 文件的情况。 比如说 SEO 工具 Screaming Frog 就只提供 DEB 软件包。 反过来,一个软件只有 RPM 格式但是没有 DEB 格式这种情况就极其罕见了。 硬件支持 一般来说,Linux 在 WiFi 适配器和显卡的兼容性上容易出现问题,Ubuntu 和 Fedora 都受此影响。 以 Nvidia 为例,它的开源驱动程序 Nouveau 经常会引发系统启动时假死机之类的问题。 在 Ubuntu 上你可以轻松安装专有驱动程序作为补充。 在很多情况下,这样可以获得对硬件更好的支持。 Installing proprietary driver is easier in Ubuntu Fedora 则坚持使用开源软件,所以在 Fedora 上安装专有驱动程序就比较困难了。 线上支持和用户群 Ubuntu 和 Fedora 都通过社区论坛提供了很好的线上支持。 Ubuntu 主要有两个论坛: UbuntuForums 和 Ask Ubuntu。 Fedora 主要的论坛则是 Ask Fedora。 就用户群体而言,Fedora 有着庞大的用户数量。 不过 Ubuntu 更为流行,用户数量甚至更为庞大。 Ubuntu 的流行催生了很多专注于 Ubuntu 的网站和博客。 所以相比 Fedora,你可以得到更多关于 Ubuntu 的故障排除指导和学习材料。 发布周期 Fedora 每六个月发布一个新版本,每个版本有九个月的支持周期。 也就是说,你必须在六个月到九个月之间进行一次系统升级。 进行 Fedora 版本升级并不是一件困难的事情,但是需要良好的网络连接。 并非所有人都喜欢每九个月进行一次 1.5 GB 的版本升级。 Ubuntu 有两种版本: 常规发布版本和长期支持(LTS)发布版本。 常规版本和 Fedora 比较类似,每隔六个月发布一次,有九个月的支持周期。 而长期支持发布版本则每两年发布一次,有五年的支持周期。 常规发布版本探索新功能特性和新的软件版本,而长期支持发布版本则支持旧版本软件。 对于不喜欢经常改变、青睐稳定性的人来说,这是一个很好的选择。 强大的基础发行版 Ubuntu 是基于 Debian 发行版的。 Debian 是最大的社区项目之一,并且也是自由软件世界里最受尊敬的项目之一。 Fedora 则是红帽公司的一个社区项目。 红帽公司是一个专注于 Linux 发行版的公司。 Fedora 充当了一个“试验田”的角色(用技术术语来说叫做“上游”),用来在红帽企业级 Linux 发布新功能之前对这些新功能进行试验。 在背后支持的企业 Ubuntu 和 Fedora 都有来自母公司的支持。 Ubuntu 源自 Canonical 公司,而 Fedora 源自红帽公司(现在是 IBM 的一部分)。 背后企业的支持非常重要,因为可以确保 Linux 发行版良好的维护。 有一些发行版是由一群独立的业余爱好者们共同创建的,但是在工作压力之下经常会结束。 你也许见过一些还算比较流行的发行版项目仅仅是因为这个原因而终止了。 很多这样的发行版由于开发者没有足够的业余时间可以投入到项目上而不得不终止,比如 Antergos 和 Korora。 Ubuntu 和 Fedora 的背后都有基于 Linux 的企业的支持,这让它们比其它独立的发行版更胜一筹。 Ubuntu vs Fedora:服务端 到目前为止,我们在 Ubuntu 和 Fedora 之间的对比主要都集中在桌面端。 不过如果不考虑一下服务端的话,对 Linux 的讨论就不能算是完整的。 Ubuntu Server Ubuntu 不仅在桌面端很流行,在服务端也有很强的存在感。 如果你能够在桌面端熟练使用 Ubuntu,那么也不会对 Ubuntu 服务器版本感到陌生。 我就是从使用 Ubuntu 桌面端开始的,现在我的网站都运行在 Ubuntu 服务器上。 Fedora 同样有服务端版本,并且也有人在使用。 但是大多数系统管理者不会喜欢一个每九个月就需要重启升级的服务器。 学习 Fedora 可以更好地帮助你使用红帽企业级 Linux(RHEL)。 RHEL 是一个付费产品,你需要购买订阅才可以使用。 如果你希望在服务器上运行一个和 Fedora 或者红帽类似的操作系统,我推荐使用 CentOS。 CentOS 同样是红帽公司附属的一个社区项目,但是专注于服务端。 结论 你可以看到,Ubuntu 和 Fedora 有很多相似之处。 不过就可用软件数量、驱动安装和线上支持来说,Ubuntu 的确更有优势。 Ubuntu 也因此成为了一个更好的选择,尤其是对于没有经验的 Linux 新手而言。 如果你想要熟悉红帽的话,Fedora 是一个很好的开始。 如果你对 Linux 有一定经验,或者是只想要使用开源软件,Fedora 就是一个很棒的选择。 最终还是需要你自己来决定是使用 Fedora 还是 Ubuntu。 我会建议为两个发行版分别创建一个 live USB,并且在虚拟机上体验一下。

Linux 命令行下搜索工具, CLI search

grep 使用 grep 的优势是它几乎可以在任意类 Unix 系统上使用。 常用 grep 命令的几种方式。 在 py 文件中找到一个关键字并且输出行号,可以这样操作: $ grep -rins --include \*.py import . 回忆起部分命令。 通过管道(|)使用 grep 命令来搜索历史记录命令: $ history | grep "python" 可以找到曾经运行过的所有包含 python 关键字的命令。 $ history | grep “python” 284 python test.py ... #省略其它结果 $ !284 $ python test.py ack 一个类似于 grep 并且为程序员优化过的工具 它在默认情况下以递归方式搜索,但是会忽略版本控制工具目录,比如 .git 目录。 并且它自带很多很实用的工具,可以大大提高我们搜索效率。 我们同样再拿出上面的例子来举例,下面我们使用 ack 命令来实现仅在 py 文件中搜索 import 关键字的方法: # ack 命令实现方式 $ ack import --py # grep 命令实现方式 $ grep -rins --include \*.py import . 上面是仅在 py 文件进行搜索,那假如我们想搜索除 py 文件类型以外的所有其他类型的文件,要怎么操作? 对于每个文件类型,都有一个对应的 no 标识,来排除对这个文件类型搜索。 比如,想搜索 py 文件的话就使用 --py 选项,而想排除 py 文件的话就使用 --nopy 选项。 $ ack import --nopy 当然文件类型有非常之多,我们还可以通过修改 ~/.ackrc 文件来扩展文件类型。 假如我们现在想搜索 .conf 文件,默认情况下 ack 不支持这种文件: $ ack hello --conf Unknown option: conf ack: Invalid option on command line 要注册 .conf 文件类型,我们可以将以下内容添加到 ~/.ackrc 文件中,之后我们就可以正常搜索 conf 文件了。 --type-set=conf=.conf 配置文件修改之后,我们可以使用 --help-types 选项来确认自定义类型是否已经成功加上。 ack 命令从 .ackrc 文件中获取配置信息,但如何你想脱离 .ackrc 文件来运行 ack 命令的话,可以使用 -noenv 选项。 The Silver Searcher 该搜索器是另一个类似于 ack 的 grep 替代品,其更快的性能让大家很推崇。 它有个非常实用的特点,那就是它会忽略在项目工程中的 .gitignore 文件所指定的文件。 所以如果你想排除搜索一些文件,就可以将那些文件写在 .gitignore 文件里。 ag 命令 在 Ubuntu 系统上可以使用以下命令来安装 ag 命令: $ apt-get install silversearcher-ag 使用 ag 命令来搜索 py 文件里包含关键字 import 的内容: $ ag import --py ag 命令十分强大,限于篇幅本文只介绍它最基本的用法,改天有时间的话再补充一下它其它非常强大的功能用法。 sift sift 是使用 Golang 编写的 grep 替代品,这意味着它可以在 Linux,Windows,OS X 和其他系统上使用。 它的速度快得离谱,而且有一些很酷的用例来代替 grep + awk 组合来提取数据。 我们再使用 sift 命令来搜索所有 py 文件里包含 import 关键字的内容: # 只搜索 py 文件: sift --ext py import # 排除 py 文件 sift --exclude-ext py import RipGrep RipGrep 与 Silver Searcher 类似,可以在 Mac、Linux 和 Windows 上运行。 它的 readme 文件声称,RipGrep 通常比其他任何搜索工具都快,它推崇 Rust 的正则表达式引擎,并像Silver Searcher一样使用 .gitignore 文件来排除一些文件或目录。 RipGrep 通常简称为 rg ,我们再使用 rg 命令来搜索所有 py 文件里包含 import 关键字的内容: rg --type=py import

Command Line Tools to Find Files in Linux

1. Find Command It supports multiple options to locate files using attributes such as permissions, users, groups, file type, date, size and other possible criteria. 2. Locate Command instead of searching through the file system when a user initiates a file search operation, locate queries a database which contains bits and parts of files and their corresponding paths on the file system. This database can be prepared and updated using the updatedb command. Note that locate will not report files created after the most recent update of the relevant database. 3. Grep Command Although grep command is not a tool for directly searching files, you can employ it to locate files. For example, if you are looking for a README.md file which contains the phrase “An assortment”, which you suspect should be somewhere in your home directory, possibly in ~/bin. $ grep -Ri ~/bin -e "An assortment" OR $ grep -Ri ~/bin/ -e "An assortment" | cut -d: -f1 Where the grep flag: -R – means search the specified directory recursively -i – means ignore case distinctions -e – specifies the phrase to be used as a pattern for searching -d – specifies the delimter -f – sets the field to be printed 4. Which Command For example: $ which find $ which locate $ which which 5. Whereis Command $ whereis find $ whereis locate $ whereis which $ whereis whereis

Linux notes.txt

============= the right-ctrl key remember to use the right-ctrl key in virtual box to switch out to windows ============= Linux text editor: gedit, pluma, vim, gvim, sublime text ============= install packages from software manager or Synaptic manager ============= # to install vim sudo apt-get install vim #edit new file test # https://www.radford.edu/~mhtay/CPSC120/VIM_Editor_Commands.htm # VIM Editor Commands https://www.fprintf.net/vimCheatSheet.html vim test hit i to insert hit esc to exit insert mode

Working with the Shell, Introduction to Bash

In the KDE taskbar, there is an icon depicting a monitor with a seashell. When you click this icon with the mouse, a console window opens in which to enter commands. The console normally runs Bash (Bourne again shell), a program developed as part of the GNU project. It is, by far, the most widely used derivative of the Bourne shell (sh). Once you have opened the shell, see the prompt on the first line. The prompt usually consists of the user name, host name, and current path, but it can be customized. When the cursor is behind this prompt, you can send commands directly to your computer system: tux $ >.

Bash: Commands

A command consists of several elements. The first element is always the actual command, followed by parameters or options. Commands are executed when you press Return. Before doing so, easily edit the command line, add options, or correct typing errors. One of the most frequently used commands is ls, which can be used with or without arguments. Entering the plain ls command in the console shows the contents of the current directory. Options are prefixed with a hyphen. The command ls -l, for instance, shows the contents of the same directory in full detail. Next to each file name, see the date when the file was created, the file size in bytes, and further details, which are covered later. One very important option that exists for many commands is the --help option. By entering ls --help, display all the options for the ls command. Also use the ls command to view the contents of other directories. To do so, the directory must be specified as a parameter. For example, to see the contents of Desktop, enter ls -l Desktop.

Bash: Files and Directories

To use the shell efficiently, it is really useful to have some knowledge about the file and directory structures of a Linux system. You can think of directories as electronic folders where files, programs, and subdirectories are stored. The top level directory in the hierarchy is the root directory, referred to as /. This is the place from which all other directories can be accessed. The /home directory contains the directories in which the individual users can store their personal files. Figure 24.1: “Excerpt from a Standard Directory Tree” shows the standard directory tree in Linux, with the home directories of the example users xyz, linux, and tux. The directory tree of a Linux system has a functional structure that follows the File System Standard. The following list provides a brief description of the standard directories in Linux. Figure 24.1. Excerpt from a Standard Directory Tree Excerpt from a Standard Directory Tree
/
root directory, starting point of the directory tree.
/home
(private) directories of users.
/dev
device files that represent hardware components
/etc
important files for system configuration.
/etc/init.d
boot scripts
/usr/bin
generally accessible programs.
/bin
programs needed early in the boot process.
/usr/sbin
programs reserved for the system administrator.
/sbin
programs reserved for the system administrator and needed for booting.
/usr/include
header files for the C compiler
/usr/include/g++
header files for the C++ compiler.
/usr/share/doc
various documentation files.
/usr/share/man
system manual pages (man pages).
/usr/src
source code of system software
/usr/src/linux
kernel source code.
/tmp, /var/tmp
temporary files.
/usr
all application programs
/var
configuration files (e.g., those linked from /usr)
/var/log
system log files
/var/adm
system administration data
/lib
shared libraries (for dynamically linked programs)
/proc
process file system.
/usr/local
local, distribution-independent extensions.
/opt
optional software, larger add-on program packages (such as KDE, GNOME, Netscape).

Bash: Functions

There are two important functions of the shell that can make your work a lot easier:

First Example: Managing Files

Now that you know what a command looks like, which directories exist in SuSE Linux, and how to speed up things when using Bash, put this knowledge into practice with a small exercise.
  1. Open a console from the KDE desktop by clicking the shell icon.
  2. Enter the ls command to see the contents of your home directory.
  3. Use the command mkdir (which stands for make directory) to create a new subdirectory called test by entering mkdir test.
  4. Now launch the KEdit editor by pressing Alt + F2 and entering kedit in the input field. Type a few letters in the editor then save the file as Testfile in your home directory. Linux distinguishes between uppercase and lowercase. For this example, use an uppercase T.
  5. View the contents of your home directory again. Instead of typing ls again, just press UpArrow twice and the ls command should reappear at the prompt. To execute the command, hit Return. The newly created directory test should appear in blue letters and Testfile in black. This is how directories and files can be distinguished in a console.
  6. Move Testfile into the subdirectory test with the command mv. To speed this up, use the expansion function: just enter mv T and press Tab. As long as there is no other file beginning with this letter in the directory, the shell expands the file name and adds the string estfile. Otherwise, add a letter or two yourself and test Tab each time to see whether the shell can now expand the name. Finally, type a space then test after the expanded file name and press Return to execute the command.
  7. At this point, Testfile should no longer be in the directory. Check this by entering ls again.
  8. To see whether the file has been successfully moved, change into the directory test with the command cd test. Now enter ls again. You should see Testfile in the listing. Change back to your home directory at any point by entering only cd (which stands for change directory).
  9. To make a copy of a file, use cp. For instance, enter cp Testfile Testbackup to copy Testfile to Testbackup. Once again, the command ls can be used to see whether both files are in the directory.

Bash: Specifying Paths

When working with files or directories, it is important specify the correct path. However, you do not need to enter the entire (absolute) path from the root directory to the respective file. Rather, you can start from the current directory. Address your home directory directly with ~. Accordingly, there are two ways to list the file Testfile in the directory test: by entering the relative path with ls test/* or by specifying the absolute path with ls ~/test/*. To list the contents of home directories of other users, enter ls ~username. In the above-mentioned directory tree, one of the sample users is tux. Thus, the command ls ~tux would list the contents of the home directory of tux. Refer to the current directory with a dot. The next higher level in the tree is represented by two dots. By entering ls .., see the contents of the parent directory of the current directory. The command ls ../.. shows the contents of the directory two levels higher in the hierarchy.

Second Example: Working with Paths

Here is another example to illustrate how to move around in the directories of your SuSE Linux system.

Bash: Wild Cards

Another convenience offered by the shell is wild cards. There are four different types of these in Bash:
?
Matches exactly one arbitrary character
*
Matches an arbitrary number of characters
[set]
Matches one of the characters from the group specified inside the square brackets, which is represented here by the string set
[!set]
Matches one character other than those identified by set
Assuming that your test directory contains the files Testfile, Testfile1, Testfile2, and datafile, the command ls Testfile? will list the files Testfile1 and Testfile2. With ls Test*, the list will also include Testfile. The command ls *fil* shows all the sample files. Finally, you can use the set wild card to address all sample files whose last character is a number: ls Testfile[1-9]. Among the four types of wild cards, the most inclusive one is the asterisk. It could be used to copy all files contained in one directory to another one or to delete all files with one command. The command rm *fil*, for instance, would delete all files in the current directory whose name includes the string fil.

Bash: More or Less

Linux includes two small programs for viewing text files directly in the shell. Rather than starting an editor to read a file like Readme.txt, simply enter less Readme.txt to display the text in the console window. Use Space to scroll down one page. Use PgUp and PgDown to move forward or backward in the text. To exit less, press Q. The program less got its name from the the precept that less is more and can also be used to view the output of commands in a convenient way. To see how this works, read Section “Pipes”. Instead of less, you can also use the older program more. However, it is less convenient because it does not allow you to scroll backwards.

Bash: Pipes

Normally, the standard output in the shell is your screen or the console window, and the standard input is the keyboard. To forward the output of a command to an application such as less, use a pipeline. To view the files in the test directory, enter the command ls test | less. The contents of the test directory will be displayed with less. This only makes sense if the normal output with ls would be too lengthy. For instance, if you view the contents of the dev directory with ls /dev, you will only see a small portion in the window. View the entire list with ls /dev | less. It is also possible to save the output of commands to a file. For example, ls test > Content generates a new file called Content that contains a list of the files and directories in test. View the file with less Content. Similarly, you can also use a file as the input for a comand. For example, sort the text lines in Testfile with sort < Testfile. The output of the command sort is sent to the screen. The text is sorted by the first letters of the individual lines. If you need a new file containing the sorted list, pipe the output of the command sort to a file. To test this, create an unsorted name list in an editor and save it under list in the test directory. Then change into test and enter the command sort < unsortedlist > sortedlist. Finally, view the sorted list with less. Just like the standard output, the standard error output is sent to the console as well. However, to redirect the standard error output to a file named errors, append 2> errors to the corresponding command. On the other hand, both standard output and standard error are saved to one file named alloutput if you append >& alloutput. Finally, to append the output of a command to an already existing file, the command must be followed by >> instead of a single >.

Bash: Archives and Data Compression

Now that you have already created a number of files and directories, consider the subject of archives and data compression. Suppose you want to have the entire test directory packed in one file that you can save on a floppy disk as a backup copy or send by e-mail. To do so, use the command tar (for tape archiver). With tar --help, view all the options for the tar command. The most important of these options are explained here:
-c
(for create) Create a new archive.
-t
(for table) Display the contents of an archive.
-x
(for extract) Unpack the archive.
-v
(for verbose) Show all files on screen while creating the archive.
-f
(for file) Choose a file name for the archive file. When creating an archive, this option must always be given as the last one.
To pack the test directory with all its files and subdirectories into an archive named testarchive.tar, use the options -c and -f. For the testing purposes of this example, also add -v to follow the progress of the archiving, although this option is not mandatory. After using cd to change to your home directory where the test directory is located, enter tar -cvf testarchive.tar test. After that, view the contents of the archive file with tar -tf testarchive.tar. The test directory with all its files and directories has remained unchanged on your hard disk. To unpack the archive, enter tar -xvf testarchive.tar, but do not try this yet. For file compression, the obvious choice on Linux is the popular gzip program. Just enter gzip testarchive.tar. With ls, now see that the file testarchive.tar is no longer there and that the file testarchive.tar.gz has been created instead. This file is much smaller and therefore much better suited for transfer via e-mail or storage on a floppy. Now, unpack this file in the test2 directory created earlier. To do so, enter cp testarchive.tar.gz test2 to copy the file to that directory. Change to the directory with cd test2. A compressed archive with the .tar.gz extension can be unzipped with the gunzip command. Enter gunzip testarchive.tar.gz , which results in the file testarchive.tar, which then needs to be extracted or untarred with tar -xvf testarchive.tar. You can also unzip and extract a compressed archive in one step by adding the -z option. The complete command would be tar -xvzf testarchive.tar.gz. With ls, you can see that a new test directory has been created with the same contents as your test directory in your home directory.

Bash: mtools

mtools are a set of commands for working with MS-DOS file systems. The commands included in mtools allow you to address the first floppy drive as a:, just like under MS-DOS, and the commands are like MS-DOS commands except they are prefixed with an m:
mdir a:
displays the contents of the floppy disk in drive a:
mcopy Testfile a:
copies the file Testfile to the floppy disk.
mdel a:Testfile
deletes Testfile in a:
mformat a:
formats the floppy disk in MS-DOS format (using the fdformat command).
mcd a:
makes a: your current directory
mmd a:test
creates the subdirectory test on the floppy disk
mrd a:test
deletes the subdirectory test from the floppy disk

Linux copy and paste

Use Ctrl+Insert or Ctrl+Shift+C for copying and Shift+Insert or Ctrl+Shift+V for pasting text in the terminal in Ubuntu. Right click and selecting the copy/paste option from the context menu is also an option. I thought of elaborating on this topic specially when there is no single universal way of copy and paste in the Linux terminal. Linux Terminal Shortcuts

30 Bash Script Examples

Create and Execute First BASH Program:
Use of echo command:
Use of comment:
Use of Multi-line comment:
Using While Loop:
Using For Loop:
Get User Input:
Using if statement:
Using if statement with AND logic:
Using if statement with OR logic:
Using else if statement:
Using Case Statement:
Get Arguments from Command Line:
Get arguments from command line with names:
Combine String variables:
Get substring of String:
Add Two Numbers:
Create Function:
Create function with Parameters:
Pass Return Value from Function:
Make Directory:
Make directory by checking existence:
Read a File:
Delete a File:
Append to File:
Test if File Exist:
Send Email:
Get Parse Current Date:
Wait Command:
Sleep Command:

Create and Execute First BASH Program:

You can run bash script from the terminal or by executing any bash file. Run the following command from the terminal to execute a very simple bash statement. The output of the command will be ‘Hello World’. $ echo "Hello World" Open any editor to create a bash file. Here, nano editor is used to create the file and filename is set as ‘First.sh’ $ nano First.sh Add the following bash script to the file and save the file. #!/bin/bash echo "Hello World" You can run bash file by two ways. One way is by using bash command and another is by setting execute permission to bash file and run the file. Both ways are shown here. $ bash First.sh Or, $ chmod a+x First.sh $ ./First.sh

Use of echo command:

You can use echo command with various options. Some useful options are mentioned in the following example. When you use ‘echo’ command without any option then a newline is added by default. ‘-n’ option is used to print any text without new line and ‘-e’ option is used to remove backslash characters from the output. Create a new bash file with a name, ‘echo_example.sh’ and add the following script. #!/bin/bash echo "Printing text with newline" echo -n "Printing text without newline" echo -e "\nRemoving \t backslash \t characters\n" Run the file with bash command. $ bash echo_example.sh

Use of comment:

‘#’ symbol is used to add single line comment in bash script. Create a new file named ‘comment_example.sh’ and add the following script with single line comment. #!/bin/bash # Add two numeric value ((sum=25+35)) #Print the result echo $sum Run the file with bash command. $ bash comment_example.sh

Use of Multi-line comment:

You can use multi line comment in bash in various ways. A simple way is shown in the following example. Create a new bash named, ‘multiline-comment.sh’ and add the following script. Here, ‘:’ and symbols are used to add multiline comment in bash script. This following script will calculate the square of 5. #!/bin/bash : ' The following script calculates the square value of the number, 5. ' ((area=5*5)) echo $area Run the file with bash command. $ bash multiline-comment.sh You can check the following link to know more about the use of bash comment. https://linuxhint.com/bash_comments/

Using While Loop:

Create a bash file with the name, ‘while_example.sh’, to know the use of while loop. In the example, while loop will iterate for 5 times. The value of count variable will increment by 1 in each step. When the value of count variable will 5 then the while loop will terminate. #!/bin/bash valid=true count=1 while [ $valid ] do echo $count if [ $count -eq 5 ]; then break fi ((count++)) done Run the file with bash command. $ bash while_example.sh You can check the following link to know more about the use of while loop. https://linuxhint.com/bash-while-loop-examples/

Using For Loop:

The basic for loop declaration is shown in the following example. Create a file named ‘for_example.sh’ and add the following script using for loop. Here, for loop will iterate for 10 times and print all values of the variable, counter in single line. #!/bin/bash for (( counter=10; counter>0; counter-- )) do echo -n "$counter " done printf "\n" Run the file with bash command. $ bash for_example.sh You can use for loop for different purposes and ways in your bash script. You can check the following link to know more about the use of for loop. https://linuxhint.com/bash-for-loop-examples/

Get User Input:

read’ command is used to take input from user in bash. Create a file named ‘user_input.sh’ and add the following script for taking input from the user. Here, one string value will be taken from the user and display the value by combining other string value. #!/bin/bash echo "Enter Your Name" read name echo "Welcome $name to LinuxHint" Run the file with bash command. $ bash user_input.sh You can check the following link to know more about the use of user input. https://linuxhint.com/bash-script-user-input/

Using if statement:

You can use if condition with single or multiple conditions. Starting and ending block of this statement is define by ‘if’ and ‘fi’. Create a file named ‘simple_if.sh’ with the following script to know the use if statement in bash. Here, 10 is assigned to the variable, n. if the value of $n is less than 10 then the output will be “It is a one digit number”, otherwise the output will be “It is a two digit number”. For comparison, ‘-lt’ is used here. For comparison, you can also use ‘-eq’ for equality, ‘-ne’ for not equality and ‘-gt’ for greater than in bash script. #!/bin/bash n=10 if [ $n -lt 10 ]; then echo "It is a one digit number" else echo "It is a two digit number" fi Run the file with bash command. $ bash simple_if.sh

Using if statement with AND logic:

Different types of logical conditions can be used in if statement with two or more conditions. How you can define multiple conditions in if statement using AND logic is shown in the following example. ‘&&’ is used to apply AND logic of if statement. Create a file named ‘if_with_AND.sh’ to check the following code. Here, the value of username and password variables will be taken from the user and compared with ‘admin’ and ‘secret’. If both values match then the output will be “valid user”, otherwise the output will be “invalid user”. !/bin/bash echo "Enter username" read username echo "Enter password" read password if [ ( $username == "admin" && $password == "secret" ) ]]; then echo "valid user" else echo "invalid user" fi Run the file with bash command. $ bash if_with_AND.sh

Using if statement with OR logic:

||’ is used to define OR logic in if condition. Create a file named ‘if_with_OR.sh’ with the following code to check the use of OR logic of if statement. Here, the value of n will be taken from the user. If the value is equal to 15 or 45 then the output will be “You won the game”, otherwise the output will be “You lost the game”. #!/bin/bash echo "Enter any number" read n if [ ( $n -eq 15 || $n -eq 45 ) ]] then echo "You won the game" else echo "You lost the game" fi Run the file with bash command. $ bash if_with_OR.sh

Using else if statement:

The use of else if condition is little different in bash than other programming language. ‘elif’ is used to define else if condition in bash. Create a file named, ‘elseif_example.sh’ and add the following script to check how else if is defined in bash script. #!/bin/bash echo "Enter your lucky number" read n if [ $n -eq 101 ]; then echo "You got 1st prize" elif [ $n -eq 510 ]; then echo "You got 2nd prize" elif [ $n -eq 999 ]; then echo "You got 3rd prize" else echo "Sorry, try for the next time" fi Run the file with bash command. $ bash elseif_example.sh

Using Case Statement:

Case statement is used as the alternative of if-elseif-else statement. The starting and ending block of this statement is defined by ‘case’ and ‘esac’. Create a new file named, ‘case_example.sh’ and add the following script. The output of the following script will be same to the previous else if example. #!/bin/bash echo "Enter your lucky number" read n case $n in 101) echo echo "You got 1st prize" ;; 510) echo "You got 2nd prize" ;; 999) echo "You got 3rd prize" ;; *) echo "Sorry, try for the next time" ;; esac Run the file with bash command. $ bash case_example.sh

Get Arguments from Command Line:

Bash script can read input from command line argument like other programming language. For example, $1 and $2 variable are used to read first and second command line arguments. Create a file named “command_line.sh” and add the following script. Two argument values read by the following script and prints the total number of arguments and the argument values as output. #!/bin/bash echo "Total arguments : $#" echo "1st Argument = $1" echo "2nd argument = $2" Run the file with bash command. $ bash command_line.sh Linux Hint You can check the following link to know more about the use of command line argument. https://linuxhint.com/command_line_arguments_bash_script/

Get arguments from command line with names:

How you can read command line arguments with names is shown in the following script. Create a file named, ‘command_line_names.sh’ and add the following code. Here, two arguments, X and Y are read by this script and print the sum of X and Y. #!/bin/bash for arg in "[email protected]" do index=$(echo $arg | cut -f1 -d=) val=$(echo $arg | cut -f2 -d=) case $index in X) x=$val;; Y) y=$val;; *) esac done ((result=x+y)) echo "X+Y=$result" Run the file with bash command and with two command line arguments. $ bash command_line_names X=45 Y=30

Combine String variables:

You can easily combine string variables in bash. Create a file named “string_combine.sh” and add the following script to check how you can combine string variables in bash by placing variables together or using ‘+’ operator. #!/bin/bash string1="Linux" string2="Hint" echo "$string1$string2" string3=$string1+$string2 string3+=" is a good tutorial blog site" echo $string3 Run the file with bash command. $ bash string_combine.sh

Get substring of String:

Like other programming language, bash has no built-in function to cut value from any string data. But you can do the task of substring in another way in bash that is shown in the following script. To test the script, create a file named ‘substring_example.sh’ with the following code. Here, the value, 6 indicates the starting point from where the substring will start and 5 indicates the length of the substring. #!/bin/bash Str="Learn Linux from LinuxHint" subStr=${Str:6:5} echo $subStr Run the file with bash command. $ bash substring_example.sh

Add Two Numbers:

You can do the arithmetical operations in bash in different ways. How you can add two integer numbers in bash using double brackets is shown in the following script. Create a file named ‘add_numbers.sh’ with the following code. Two integer values will be taken from the user and printed the result of addition. #!/bin/bash echo "Enter first number" read x echo "Enter second number" read y (( sum=x+y )) echo "The result of addition=$sum" Run the file with bash command. $ bash add_numbers.sh You can check the following link to know more about bash arithmetic. https://linuxhint.com/bash_arithmetic_operations/

Create Function:

How you can create a simple function and call the function is shown in the following script. Create a file named ‘function_example.sh’ and add the following code. You can call any function by name only without using any bracket in bash script. #!/bin/bash function F1() { echo 'I like bash programming' } F1 Run the file with bash command. $ bash function_example.sh

Create function with Parameters:

Bash can’t declare function parameter or arguments at the time of function declaration. But you can use parameters in function by using other variable. If two values are passed at the time of function calling then $1 and $2 variable are used for reading the values. Create a file named ‘function|_parameter.sh’ and add the following code. Here, the function, ‘Rectangle_Area’ will calculate the area of a rectangle based on the parameter values. #!/bin/bash Rectangle_Area() { area=$(($1 * $2)) echo "Area is : $area" } Rectangle_Area 10 20 Run the file with bash command. $ bash function_parameter.sh

Pass Return Value from Function:

Bash function can pass both numeric and string values. How you can pass a string value from the function is shown in the following example. Create a file named, ‘function_return.sh’ and add the following code. The function, greeting() returns a string value into the variable, val which prints later by combining with other string. #!/bin/bash function greeting() { str="Hello, $name" echo $str } echo "Enter your name" read name val=$(greeting) echo "Return value of the function is $val" Run the file with bash command. $ bash function_return.sh You can check the following link to know more about the use of bash function. https://linuxhint.com/return-string-bash-functions/

Make Directory:

Bash uses ‘mkdir’ command to create a new directory. Create a file named ‘make_directory.sh’ and add the following code to take a new directory name from the user. If the directory name is not exist in the current location then it will create the directory, otherwise the program will display error. #!/bin/bash echo "Enter directory name" read newdir `mkdir $newdir` Run the file with bash command. $ bash make_directory.sh

Make directory by checking existence:

If you want to check the existence of directory in the current location before executing the ‘mkdir’ command then you can use the following code. ‘-d’ option is used to test a particular directory is exist or not. Create a file named, ‘directory_exist.sh’ and add the following code to create a directory by checking existence. #!/bin/bash echo "Enter directory name" read ndir if [ -d "$ndir" ] then echo "Directory exist" else `mkdir $ndir` echo "Directory created" fi Run the file with bash command. $ bash directory_exist.sh You can check the following link to know more about directory creation. https://linuxhint.com/bash_mkdir_not_existent_path/

Read a File:

You can read any file line by line in bash by using loop. Create a file named, ‘read_file.sh’ and add the following code to read an existing file named, ‘book.txt’. #!/bin/bash file='book.txt' while read line; do echo $line done < $file Run the file with bash command. $ bash read_file.sh Run the following command to check the original content of ‘book.txt’ file. $ cat book.txt You can check the following link to know the different ways to read file. https://linuxhint.com/read_file_line_by_line_bash/

Delete a File:

rm’ command is used in bash to remove any file. Create a file named ‘delete_file.sh’ with the following code to take the filename from the user and remove. Here, ‘-i’ option is used to get permission from the user before removing the file. #!/bin/bash echo "Enter filename to remove" read fn rm -i $fn Run the file with bash command. $ ls $ bash delete_file.sh $ ls

Append to File:

New data can be added into any existing file by using ‘>>’ operator in bash. Create a file named ‘append_file.sh’ and add the following code to add new content at the end of the file. Here, ‘Learning Laravel 5’ will be added at the of ‘book.txt’ file after executing the script. #!/bin/bash echo "Before appending the file" cat book.txt echo "Learning Laravel 5">> book.txt echo "After appending the file" cat book.txt Run the file with bash command. $ bash append_file.sh

Test if File Exist:

You can check the existence of file in bash by using ‘-e’ or ‘-f’ option. ‘-f’ option is used in the following script to test the file existence. Create a file named, ‘file_exist.sh’ and add the following code. Here, the filename will pass from the command line. #!/bin/bash filename=$1 if [ -f "$filename" ]; then echo "File exists" else echo "File does not exist" fi Run the following commands to check the existence of the file. Here, book.txt file exists and book2.txt is not exist in the current location. $ ls $ bash file_exist.sh book.txt $ bash file_exist.sh book2.txt

Send Email:

You can send email by using ‘mail’ or ‘sendmail’ command. Before using these commands, you have to install all necessary packages. Create a file named, ‘mail_example.sh’ and add the following code to send the email. #!/bin/bash Recipient=”admin@example.com” Subject=”Greeting” Message=”Welcome to our site” `mail -s $Subject $Recipient <<< $Message` Run the file with bash command. $ bash mail_example.sh

Get Parse Current Date:

You can get the current system date and time value using `date` command. Every part of date and time value can be parsed using ‘Y’, ‘m’, ‘d’, ‘H’, ‘M’ and ‘S’. Create a new file named ‘date_parse.sh’ and add the following code to separate day, month, year, hour, minute and second values. #!/bin/bash Year=`date +%Y` Month=`date +%m` Day=`date +%d` Hour=`date +%H` Minute=`date +%M` Second=`date +%S` echo `date` echo "Current Date is: $Day-$Month-$Year" echo "Current Time is: $Hour:$Minute:$Second" Run the file with bash command. $ bash date_parse.sh

Wait Command:

wait is a built-in command of Linux that waits for completing any running process. wait command is used with a particular process id or job id. If no process id or job id is given with wait command then it will wait for all current child processes to complete and returns exit status. Create a file named ‘wait_example.sh’ and add the following script. #!/bin/bash echo "Wait command" & process_id=$! wait $process_id echo "Exited with status $?" Run the file with bash command. $ bash wait_example.sh You can check the following link to know more about wait command.
Wait Command in Linux

Sleep Command:

When you want to pause the execution of any command for specific period of time then you can use sleep command. You can set the delay amount by seconds (s), minutes (m), hours (h) and days (d). Create a file named ‘sleep_example.sh’ and add the following script. This script will wait for 5 seconds after running. #!/bin/bash echo “Wait for 5 seconds” sleep 5 echo “Completed” Run the file with bash command. $ bash sleep_example.sh You can check the following link to know more about sleep command. https://linuxhint.com/sleep_command_linux/

Bash scripting cheatsheet

Getting started
Introduction
Variables
String quotes
Shell execution
Conditional execution
Functions
Conditionals
Strict mode
Brace expansion
Parameter expansions
Basics
Substitution
Comments
Substrings
Length
Manipulation
Default values
Loops
Basic for loop
C-like for loop
Ranges
Reading lines
Forever
Functions
Defining functions
Returning values
Raising errors
Arguments
Conditionals
Conditions
File conditions
Arrays
Defining arrays
Working with arrays
Operations
Iteration
Dictionaries
Defining
Working with dictionaries
Iteration
Options
Options
Glob options
History
Commands
Expansions
Operations
Slices
Miscellaneous
Numeric calculations
Subshells
Redirection
Inspecting commands
Trap errors
Case/switch
Source relative
printf
Directory of script
Getting options
Heredoc
Reading input
Special variables
Go to previous directory
Check for command’s result
Grep check

Getting started

Introduction

This is a quick reference to getting started with Bash scripting. Learn bash in y minutes (learnxinyminutes.com) Bash Guide (mywiki.wooledge.org) #!/usr/bin/env bash NAME="John" echo "Hello $NAME!"

Variables

NAME="John" echo $NAME echo "$NAME" echo "${NAME}!"

String quotes

NAME="John" echo "Hi $NAME" #=> Hi John echo 'Hi $NAME' #=> Hi $NAME

Shell execution

echo "I'm in $(pwd)" echo "I'm in `pwd`" # Same See Command substitution

Conditional execution

git commit && git push git commit || echo "Commit failed"

Functions

get_name() { echo "John" } echo "You are $(get_name)" See: Functions

Conditionals

if [[ -z "$string" ]]; then echo "String is empty" elif [[ -n "$string" ]]; then echo "String is not empty" fi See: Conditionals

Strict mode

set -euo pipefail IFS=$'\n\t' See: Unofficial bash strict mode

Brace expansion

echo {A,B}.js
Expression Description
{A,B}Same as A B
{A,B}.jsSame as A.js B.js
{1..5}Same as 1 2 3 4 5
See: Brace expansion

Parameter expansions

Basics

name="John" echo ${name} echo ${name/J/j} #=> "john" (substitution) echo ${name:0:2} #=> "Jo" (slicing) echo ${name::2} #=> "Jo" (slicing) echo ${name::-1} #=> "Joh" (slicing) echo ${name:(-1)} #=> "n" (slicing from right) echo ${name:(-2):1} #=> "h" (slicing from right) echo ${food:-Cake} #=> $food or "Cake" length=2 echo ${name:0:length} #=> "Jo" See: Parameter expansion STR="/path/to/foo.cpp" echo ${STR%.cpp} # /path/to/foo echo ${STR%.cpp}.o # /path/to/foo.o echo ${STR%/*} # /path/to echo ${STR##*.} # cpp (extension) echo ${STR##*/} # foo.cpp (basepath) echo ${STR#*/} # path/to/foo.cpp echo ${STR##*/} # foo.cpp echo ${STR/foo/bar} # /path/to/bar.cpp STR="Hello world" echo ${STR:6:5} # "world" echo ${STR: -5:5} # "world" SRC="/path/to/foo.cpp" BASE=${SRC##*/} #=> "foo.cpp" (basepath) DIR=${SRC%$BASE} #=> "/path/to/" (dirpath)

Substitution

Code Description
${FOO%suffix}Remove suffix
${FOO#prefix}Remove prefix
${FOO%%suffix}Remove long suffix
${FOO##prefix}Remove long prefix
${FOO/from/to}Replace first match
${FOO//from/to}Replace all
${FOO/%from/to}Replace suffix
${FOO/#from/to}Replace prefix

Comments

# Single line comment : ' This is a multi line comment '

Substrings

Expression Description
${FOO:0:3}Substring (position, length)
${FOO:(-3):3}Substring from the right

Length

Expression Description
${#FOO}Length of $FOO

Manipulation

STR="HELLO WORLD!" echo ${STR,} #=> "hELLO WORLD!" (lowercase 1st letter) echo ${STR,,} #=> "hello world!" (all lowercase) STR="hello world!" echo ${STR^} #=> "Hello world!" (uppercase 1st letter) echo ${STR^^} #=> "HELLO WORLD!" (all uppercase)

Default values

Expression Description
${FOO:-val}$FOO, or val if unset (or null)
${FOO:=val}Set $FOO to val if unset (or null)
${FOO:+val}val if $FOO is set (and not null)
${FOO:?message}Show error message and exit if $FOO is unset (or null)
Omitting the : removes the (non)nullity checks, e.g. ${FOO-val} expands to val if unset otherwise $FOO.

Loops

Basic for loop

for i in /etc/rc.*; do echo $i done

C-like for loop

for ((i = 0 ; i < 100 ; i++)); do echo $i done

Ranges

for i in {1..5}; do echo "Welcome $i" done

With step size

for i in {5..50..5}; do echo "Welcome $i" done

Reading lines

cat file.txt | while read line; do echo $line done

Forever

while true; do ··· done

Functions

Defining functions

myfunc() { echo "hello $1" } # Same as above (alternate syntax) function myfunc() { echo "hello $1" } myfunc "John"

Returning values

myfunc() { local myresult='some value' echo $myresult } result="$(myfunc)"

Raising errors

myfunc() { return 1 } if myfunc; then echo "success" else echo "failure" fi

Arguments

Expression Description
$#Number of arguments
$*All positional arguments (as a single word)
$@All positional arguments (as separate strings)
$1First argument
$_Last argument of the previous command
Note: $@ and $* must be quoted in order to perform as described. Otherwise, they do exactly the same thing (arguments as separate strings). See Special parameters.

Conditionals

Conditions

Note that [[ is actually a command/program that returns either 0 (true) or 1 (false). Any program that obeys the same logic (like all base utils, such as grep(1) or ping(1)) can be used as condition, see examples.
Condition Description
[[ -z STRING ]]Empty string
[[ -n STRING ]]Not empty string
[[ STRING == STRING ]]Equal
[[ STRING != STRING ]]Not Equal
[[ NUM -eq NUM ]]Equal
[[ NUM -ne NUM ]]Not equal
[[ NUM -lt NUM ]]Less than
[[ NUM -le NUM ]]Less than or equal
[[ NUM -gt NUM ]]Greater than
[[ NUM -ge NUM ]]Greater than or equal
[[ STRING =~ STRING ]]Regexp
(( NUM < NUM ))Numeric conditions

More conditions

Condition Description
[[ -o noclobber ]]If OPTIONNAME is enabled
[[ ! EXPR ]]Not
[[ X && Y ]]And
[[ X || Y ]]Or

File conditions

Condition Description
[[ -e FILE ]]Exists
[[ -r FILE ]]Readable
[[ -h FILE ]]Symlink
[[ -d FILE ]]Directory
[[ -w FILE ]]Writable
[[ -s FILE ]]Size is > 0 bytes
[[ -f FILE ]]File
[[ -x FILE ]]Executable
[[ FILE1 -nt FILE2 ]]1 is more recent than 2
[[ FILE1 -ot FILE2 ]]2 is more recent than 1
[[ FILE1 -ef FILE2 ]]Same files
# String if [[ -z "$string" ]]; then echo "String is empty" elif [[ -n "$string" ]]; then echo "String is not empty" else echo "This never happens" fi # Combinations if [[ X && Y ]]; then ... fi # Equal if [[ "$A" == "$B" ]] # Regex if [[ "A" =~ . ]] if (( $a < $b )); then echo "$a is smaller than $b" fi if [[ -e "file.txt" ]]; then echo "file exists" fi

Arrays

Defining arrays

Fruits=('Apple' 'Banana' 'Orange') Fruits[0]="Apple" Fruits[1]="Banana" Fruits[2]="Orange"

Working with arrays

echo ${Fruits[0]} # Element #0 echo ${Fruits[-1]} # Last element echo ${Fruits[@]} # All elements, space-separated echo ${#Fruits[@]} # Number of elements echo ${#Fruits} # String length of the 1st element echo ${#Fruits[3]} # String length of the Nth element echo ${Fruits[@]:3:2} # Range (from position 3, length 2) echo ${!Fruits[@]} # Keys of all elements, space-separated

Operations

Fruits=("${Fruits[@]}" "Watermelon") # Push Fruits+=('Watermelon') # Also Push Fruits=( ${Fruits[@]/Ap*/} ) # Remove by regex match unset Fruits[2] # Remove one item Fruits=("${Fruits[@]}") # Duplicate Fruits=("${Fruits[@]}" "${Veggies[@]}") # Concatenate lines=(`cat "logfile"`) # Read from file

Iteration

for i in "${arrayName[@]}"; do echo $i done

Dictionaries

Defining

declare -A sounds sounds[dog]="bark" sounds[cow]="moo" sounds[bird]="tweet" sounds[wolf]="howl" Declares sound as a Dictionary object (aka associative array).

Working with dictionaries

echo ${sounds[dog]} # Dog's sound echo ${sounds[@]} # All values echo ${!sounds[@]} # All keys echo ${#sounds[@]} # Number of elements unset sounds[dog] # Delete dog

Iteration

Iterate over values

for val in "${sounds[@]}"; do echo $val done

Iterate over keys

for key in "${!sounds[@]}"; do echo $key done

Options

Options

set -o noclobber # Avoid overlay files (echo "hi" > foo) set -o errexit # Used to exit upon error, avoiding cascading errors set -o pipefail # Unveils hidden failures set -o nounset # Exposes unset variables

Glob options

shopt -s nullglob # Non-matching globs are removed ('*.foo' => '') shopt -s failglob # Non-matching globs throw errors shopt -s nocaseglob # Case insensitive globs shopt -s dotglob # Wildcards match dotfiles ("*.sh" => ".foo.sh") shopt -s globstar # Allow ** for recursive matches ('lib/**/*.rb' => 'lib/a/b/c.rb') Set GLOBIGNORE as a colon-separated list of patterns to be removed from glob matches.

History

Commands

Command Description
historyShow history
shopt -s histverifyDon’t execute expanded result immediately

Expansions

Expression Description
!$Expand last parameter of most recent command
!*Expand all parameters of most recent command
!-nExpand nth most recent command
!nExpand nth command in history
!<command>Expand most recent invocation of command <command>

Operations

Code Description
!!Execute last command again
!!:s/<FROM>/<TO>/Replace first occurrence of <FROM> to <TO> in most recent command
!!:gs/<FROM>/<TO>/Replace all occurrences of <FROM> to <TO> in most recent command
!$:tExpand only basename from last parameter of most recent command
!$:hExpand only directory from last parameter of most recent command
!! and !$ can be replaced with any valid expansion.

Slices

Code Description
!!:nExpand only nth token from most recent command (command is 0; first argument is 1)
!^Expand first argument from most recent command
!$Expand last token from most recent command
!!:n-mExpand range of tokens from most recent command
!!:n-$Expand nth token to last from most recent command
!! can be replaced with any valid expansion i.e. !cat, !-2, !42, etc.

Miscellaneous

Numeric calculations

$((a + 200)) # Add 200 to $a $(($RANDOM%200)) # Random number 0..199

Subshells

(cd somedir; echo "I'm now in $PWD") pwd # still in first directory

Redirection

python hello.py > output.txt # stdout to (file) python hello.py >> output.txt # stdout to (file), append python hello.py 2> error.log # stderr to (file) python hello.py 2>&1 # stderr to stdout python hello.py 2>/dev/null # stderr to (null) python hello.py &>/dev/null # stdout and stderr to (null) python hello.py < foo.txt # feed foo.txt to stdin for python diff <(ls -r) <(ls) # Compare two stdout without files

Inspecting commands

command -V cd #=> "cd is a function/alias/whatever"

Trap errors

trap 'echo Error at about $LINENO' ERR or traperr() { echo "ERROR: ${BASH_SOURCE[1]} at about ${BASH_LINENO[0]}" } set -o errtrace trap traperr ERR

Case/switch

case "$1" in start | up) vagrant up ;; *) echo "Usage: $0 {start|stop|ssh}" ;; esac

Source relative

source "${0%/*}/../share/foo.sh"

printf

printf "Hello %s, I'm %s" Sven Olga #=> "Hello Sven, I'm Olga printf "1 + 1 = %d" 2 #=> "1 + 1 = 2" printf "This is how you print a float: %f" 2 #=> "This is how you print a float: 2.000000"

Directory of script

DIR="${0%/*}"

Getting options

while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in -V | --version ) echo $version exit ;; -s | --string ) shift; string=$1 ;; -f | --flag ) flag=1 ;; esac; shift; done if [[ "$1" == '--' ]]; then shift; fi

Heredoc

cat <<END hello world END

Reading input

echo -n "Proceed? [y/n]: " read ans echo $ans read -n 1 ans # Just one character

Special variables

Expression Description
$?Exit status of last task
$!PID of last background task
$$PID of shell
$0Filename of the shell script
$_Last argument of the previous command
See Special parameters.

Go to previous directory

pwd # /home/user/foo cd bar/ pwd # /home/user/foo/bar cd - pwd # /home/user/foo

Check for command’s result

if ping -c 1 google.com; then echo "It appears you have a working internet connection" fi

Grep check

if grep -q 'foo' ~/.bash_history; then echo "You appear to have typed 'foo' in the past" fi

Calculating Fire Fighter Shifts with Code BASH

A="$(date -d 2013-05-01 +%s)" B="$(date -d 2013-05-02 +%s)" C="$(date -d 2013-05-03 +%s)" today="$(date +%F)" A=$(( ( 'date -d "$today" +%s`=$A ) /(24*3600)%3 )) B=$(( ( 'date -d "$today" +%s`=$B ) /(24*3600)%3 )) C=$(( ( 'date -d "$today" +%s`=$C ) /(24*3600)%3 )) [[ "$A"==0 ]] && echo "Today is A Shift" [[ "$B"==0 ]] && echo "Today is B Shift” [[ "sC"==0 ]] && echo "Today is C Shift"

35 Bash Script Examples

1. First Bash Program
2. Echo commands
3. Use of comment
4. Multiline comment
5. While Loop
6. For Loop
7. Get User Input
8. If statement
9. Use of if statement together with AND logic
10. Use if statement with OR logic
11. Use of else if statement
12. case statement
13. Obtaining arguments from Command Line
14. Obtain arguments from command-line with names
15. Integrated string variables
16. How to Obtain a substring of string
17. Addition of two numbers
18. function creation
19. Functionality creation with parameters
20. Passing a return a value from a function
21. Make Directory
22. Creation of a directory by checking its existence
23. Reading a file
24. File Deleting
25. Append or adding to file
26. Test File existence
27. Send Email
28. Parse Current Date
29. The Wait command
30. The Sleep Command
31. The AND Operator
32. The OR Operator
33. The switch construct
34. Concatenating strings
35. Slicing strings
Conclusion


Generally, all Linux users must acquaint themselves with the basic knowledge of bash script programming because of the importance it offers.

1. First Bash Program

To get a bash file up and running, you need to execute it by running a terminal command. For instance, if we run “Hello World” in our terminal, the output we get will be “Hello World.” First Bash Program To create a bash file, you can use any text editor installed in your operating system. In this case, we will use the nano editor for creating the file. Let us name our file ‘First.sh’. Execute the command using the following command: nano First.sh Add the following bash script to the file before saving the file. #!/bin/bash echo “Hello World” How to create a bash file There are different ways of running bash commands. For instance, below are two distinct examples of executing bash. ./First.sh Alternatively, you can use execute the command below: chmod a+x First.sh ./First.sh How to execute Bash

2. Echo commands

echo commands have numerous options for selection. For instance, there is an addition of a new line by default if you use the ‘echo’ command without any other option. Alternatively, you can use ‘-n’ to print any text without a new line. Make use of the ‘-e’ command to remove backslash characters from the given output. To demonstrate this, create a bash file named ‘echo_example.sh’. After that, add the script below #!/bin/bash Echo “printing text with newline” Echo -n “printing text without newline” Echo -e “\nRemoving \t backslash \t characters\ After adding the script, execute the file with the command below: bash echo_example.sh Echo commands Illustration

3. Use of comment

While using comments, we use the “#” symbol to add a single line comment in bash scripting. Here, you will create a new file with a simple name such as ‘comment_example’. Include a script with a single comment like the example displayed below. #!/bin /bash # Add two values ((sum 30+20)) #thereafter print the result echo $sum execute the file with bash command-line Use of comment

4. Multiline comment

In bash, the multiline comment is applicable in different ways. To prove this, create a new bash named, ‘multiline-comment example.sh’, after that, add ‘:’ and “ ’ ” scripts symbols to add a multi-line comment in the script. The following example will execute the square of 2. #!bin/bash : ‘ The script written below is used to calculate the square of 2 ‘ ((area=2*2)) echo$area execute the file with bash command-line bash multiline-comment-example.sh Multiline comment illustration

5. While Loop

For easy comprehension of this bash script, create a file named ‘while_sample.sh’. The while loop will repeat five times before terminating the process. While looping, the count variable increases the count by 1 in every step till the fifth time when the loop stops. #!/bin/bash valid=True count=1 while [$valid ] do echo $count if [$count -eq 5 ]; then break fi ((count++)) done execute the file with bash command-line bash while_example.sh While Loop illustration

6. For Loop

Take a look at the following for loop example. After creating a file named ‘for_sample.sh’, add the script using ‘for loop’. This process will re-occur 12 times. After that, it will display the fields in a single line, as shown below; #!/bin/bash for (( counter=10; counter>0; counter-- )) do echo -n "$counter " done printf "\n" Execute the command by running the code below bash for_sample.sh For Loop Illustration

7. Get User Input

To get user input from bash, we will use the ‘read’ command. Follow the simple steps below to achieve the expected results. First, create a file named ‘user_feedin.sh’ and include the script below to get the user input. One value will be taken and displayed by combining other string values. As indicated below, #!/bin/bash echo "Enter Your Name" read name echo "Welcome $name to FossLinux" execute the file with bash command-line bash user_feedin.sh Get User Input Illustration

8. If statement

The if statement is used by both multiple and single conditions. A definition of ‘if’ and ‘fi’ are used Before and after an if statement. To easily understand the if statement in bash, we shall use an example. Create a file named ‘example_if.sh’. For instance, the number 4 is assigned a variable ‘s.’ If the number is divisible by 2, then the output will be “it is divisible by 2”; otherwise, if the number is not divisible by 2, then the outcome will be “it is not divisible by 2”. The ‘-lt’, in this case, is used for comparison purposes. Another comparison feature is ‘-eq.’ ‘-ne’, on the other hand, is used to show inequality while ‘-gt’ shows if a value is more significant in bash script. #!/bin/bash s=4 if [ $s / 2 ]; then echo "It is not divisible by 2" else echo "It is divisible by 2" fi execute the file with bash command-line bash example_if.sh If statement Illustration

9. Use of if statement together with AND logic

Various logical conditions can be used with the if statement whenever there are two or more conditions. The example below shows how the logic “AND” is used in defining multiple conditions in an if statement. The “&&” symbols represent the “AND” logic in a bash script. Create a file named ‘if_plus_AND.sh’. In this example, the username and password variables entered by the user will be compared with the “main” and “users” directory to see if they match. If they do, the process will be successful, thus displaying “valid-user” as the output. Otherwise, if they do not match, the outcome will be “invalid user.” !/bin/bash echo "input username" read username echo "input password" read password if [[ ( $username == "main" && $password == "users" ) ]]; then echo "valid user" else echo "invalid user" fi Execute the file using the bash command-line bash if_plus_AND.sh Use of if statement with AND logic illustration. Use if statement with AND logic Illustration The first example shows authentication failure since the user-provided does not match with the main fields. The second examples show successful authentication since the provided fields matched with the main fields.

10. Use if statement with OR logic

When using OR with the if function, the ‘||’ symbol is used. To demonstrate this, we will create a file named ‘if_with_OR.sh’ to check the use of OR logic in an IF statement. Take an instance of value ‘s’ being assigned to two numbers (10 or 40). If a user inputs either of the given numbers, then the system’s output will be “Well Played”; otherwise, the result shown will be “Sorry, You Failed.” If you examine this example, you will notice that the value of s is generated from the user. #!/bin/bash echo "Enter any number" read s if [[ ( $s -eq 10 || $n -eq 40 ) ]] then echo "Well Played" else echo "Sorry, You Failed" fi execute the file with bash command-line bash if_with_OR.sh Use if statement with OR logic Illustration As indicated in the example above, 5 is not equal to 10 or 40. Therefore, the output displays “Sorry, You Failed,” In the figure above, the user was prompted to enter any number, and he/she chose 10, and the output given is “Well Played” since 10==10

11. Use of else if statement

Many conditional statements are nearly the same despite the programming languages you choose. However, in bash programming, the use of the ‘else if’ condition is kind of different. In bash, Elif is used in place of the else if condition. We will create a file named ‘elseif_instance.sh’ then add the bash script for demonstration purposes. echo "Enter your lucky number" read n if [ $n -eq 50 ]; then echo "You won the 1st bravo!!!!" elif [ $n -eq 100 ]; then echo "You won the 2nd congrats!!!!" elif [ $n -eq 500 ]; then echo "You won the 3rd congrats!!!!" else echo "Sorry, you have to keep trying pal" fi Execute the file with bash command-line Bash elseif_instance.sh use of else if statement Illustration The execution above displays the three instances done by bash.

12. case statement

Have you ever heard of the “if-elseif-else” statement? If not, don’t worry, as it will be covered here. The Case statement is used as a substitute for the if-elseif-else statement. ‘Case’ and ‘esac’ delineate the starting and ending block respectively while using this statement. For more elaboration, an example will be of great help. Create a file named ‘case_example.sh’. After that, include the script provided below. Then, take a look at the output and compare it to the previous one. You will notice that the outcomes of both the case statement and if-elseif-else statements are the same. #!/bin/bash echo "Input your Lucky Number" read s case $s in 50) echo echo "You won the 1st bravo!!!!" ;; 100) echo "You won the 2nd congrats!!!!" ;; 500) echo "You won the 3rd congrats" ;; *) echo "Sorry, you have to keep trying pal" ;; esac execute the file with bash command-line bash case_example.sh case statement Illustration

13. Obtaining arguments from Command Line

Bash script can emulate how other programming languages obtain inputs from the command line. Look at an instance where variables $1 and $3 are used to cypher through the first and third command-line arguments, respectively. For more elaboration, let’s create a file named ‘command-line.sh’ and include the script below. In the end, the output given is the print of the total count of arguments read by the script. #!/bin/bash echo "Total arguments : $#" echo "1st Argument = $1" echo "3rd argument = $3" Execute the file with bash command-line bash command_line.sh Foss Linux Website Obtaining arguments from Command Line Illustration

14. Obtain arguments from command-line with names

This section demonstrates how to read command-line arguments that contain names. To do this, create a file named ‘command_line_names.sh’. After that, add a code with two arguments: A, B, to be read by the script and compute the sum of A and B. #!/bin/bash for arg in "$@" do index=$(echo $arg | cut -f1 -d=) val=$(echo $arg | cut -f2 -d=) case $index in A) a=$val;; B) b=$val;; *) esac done ((result=a+b)) echo "A+B=$result" Execution with bash command. The code below is a combination of the two command-line arguments. bash command_line_names.sh A=10 B=16 Obtain arguments from command-line with names Illustration

15. Integrated string variables

Bash has some significant advantages that aid a programmer to accomplish tasks quickly. String variable integration is a combination of two or more variables. To demonstrate this, create a file named ‘string_combination.sh’. After that, add the script provided below and look at how you can integrate string variables by placing variables together using the ‘+’ operator. #!/bin/bash stringA="Foss" stringB="Linux" echo "$stringA$stringB" stringC=$stringA+$stringB stringC+=" has the best online tutorials" echo $stringC execute the file with bash command-line bash string_combination.sh Integrated string variables Illustration

16. How to Obtain a substring of string

Bash lacks an inbuilt function to truncate values from a data string, just like other programming languages. However, bash allows you to carry out substring truncation differently, as shown in the script below. Create a file named ‘substring_example.sh’. In this case, the value 7 shows the substring’s protrusive point, whereas 6 shows the substring’s total length. #!/bin/bash Str="Get connected to FossLinux blogsite" subStr=${Str:4:9} echo $subStr Execution with bash command bash substring_example.sh How to Obtain a substring of string Illustration

17. Addition of two numbers

Bash supports arithmetic operations in various and complex ways. To display the complex advantages of bash, you will do the sum of two integers using double brackets, as shown below. First, you will create a file named ‘sum_numbers.sh’ using the code below. The function will prompt the user to enter the first digit, then the second digit, and finally, print the result, which computes the user’s two integers. #!/bin/bash echo "input first digit 1" read a echo "input digit 2" read b (( sum=a+b )) echo "Result=$sum" Execute the file with bash command-line bash sum_numbers.sh Addition of two numbers Illustration

18. function creation

Bash scripting allows the user to create a function and call the same function. This has been demonstrated in the example below. Create a file named ‘function_example.sh’ and input the code outline in the sample. Here, you will select any function randomly by name without specifying any kind of bash script brackets. #!/bin/bash function x() { echo 'I love fosslinux' } x Execute the file using the command-line below; bash function_example.sh function creation Illustration

19. Functionality creation with parameters

In bash programming, you can use parameters in a function by using other variables. Call the 1st value $1 and the second value $2 in an instance where the two values are called simultaneously with the function to read the values. To ascertain this, you will create a file named ‘function_parameter.sh’. Let us find the area of a rectangle ‘Rectangle_Area’ using the given parameters. #!/bin/bash Rectangle_Area() { area=$(($1 * $2)) echo "Area is : $area" } Rectangle_Area 15 25 Execute the file with the bash command. bash function_parameter.sh Functionality creation with parameters Illustration

20. Passing a return a value from a function

When dealing with returning values in bash programming, bash has a built-in function that allows the passing of numeric and string values. The following example shows the passing of string values in a function. You will create a file named ‘function_return.sh’ and include the code below for easy comprehension. The function grow() returns a string value into the variable, which later outputs the integrated string results. #!/bin/bash function greeting() { str="Goodmorning, $fname" echo $str } echo "Input your fname" read fname val=$(greeting) echo "Return value of the function is $val" Execute the file with bash command-line bash function_return.sh Passing a return a value from a function Illustration

21. Make Directory

‘Mkdir’ is a command used to create a new directory. This command means ‘make directory’. Create a file named ‘make_directory.sh’. After that, input a code that will create a new directory. Bash will create a new directory for you. #!/bin/bash echo "Input a new directory name" read newdir `mkdir $newdir` Execute the file with bash command-line bash make_directory.sh Make Directory Illustration

22. Creation of a directory by checking its existence

‘-d’ is a command that aids the user to check for an existing directory in the current computer location or not. This prevents one from executing the ‘mkdir’ command when not sure whether a directory is there or not. For demonstration, create a file named ‘directory_exists.sh’ and add the code written below to check any directory exists. #!/bin/bash echo "New directory name input" read ndir if [ -d "$ndir" ] then echo "The Directory given exists" else `mkdir $ndir`echo "Directory created" fi Execution with bash command. Bash directory_exists.sh Creation of a directory by checking its existence Illustration

23. Reading a file

Bash has a looping functionality that helps the user to read any file. Here we will showcase the easiest way to make you understand. We will do so by creating an example file named ‘read_file.sh’ and add the code below to determine the existing file called ‘langeages.txt.’ #!/bin/bash file='languages.txt' while read line; do echo $line done < $file Execute the file with bash command-line bash read_file.sh Reading a file Illustration To check the original content of languages.txt, run the command below. cat languages.txt

24. File Deleting

In bash programming, an ‘rm’ command is used to remove or delete files. We will delete a file using the ‘rm’ command. First, create a file named ‘delete_file.sh’. After that, use the code highlighted below to make the initial user’s file name and remove it. The ‘-i’ command is helpful as it allows the users to delete the file. #!/bin/bash echo "Insert a filename to delete" read filename rm -i $filename Execute the file with bash command-line. bash delete_file.sh File Deleting Illustration

25. Append or adding to file

With an existing file, bash has a ‘>>’ operator that allows appending of new data into the file. To test this, create a file named ‘add_file.sh’. Then add a code that will add data to the end of the current file. Add the following string, ‘studying angular,’ to the ‘languages.txt’ file after running the bash script. #!/bin/bash echo "Before adding the file" cat languages.txt echo "Studying angular">> languages.txt echo "After adding the file" cat languages.txt Execution with bash command. bash add_file.sh Append or adding to file Illustration

26. Test File existence

Bash has great user functionalities that make it user-friendly. In this section, we will see the functionality that gives you an option of checking whether a particular file exists or not. The ‘-e’ or ‘-f’ commands will aid us in checking if a file exists or not. To test this, create a file named ‘file_exist.sh’, then add the code below. In this test, the filename will pass from the command line. #!/bin/bash filename=$1 if [ -f "$filename" ]; then echo "File exists" else echo "File does not exist" fi Run the commands displayed below to confirm the existence of the files. In this example, the languages.txt file is available, whereas the languages1.txt file does not exist. ls bash file_exist.sh languages.txt bash file_exist.sh languages1.txt Test File existence Illustration These commands are used to check whether a file being looked for exists or not. For instance, in this example, the languages.txt file exists, while the languages1.txt does not exist.

27. Send Email

The ‘mail’ or ‘sendmail’ commands in a bash script are used to send emails. These commands will work efficiently after installing all the necessary packages. For demonstration purposes, create a file named ‘mail_example.sh’. Use the codes highlighted below to send the intended email. #!/bin/bash Recipient=”fosslinux@example.com” Subject=”inquiries” Message=”Need anything from fosslinux blogsite?” `mail -s $Subject $Recipient <<< $Message` Execute the file with the bash command. bash mail_example.sh

28. Parse Current Date

Bash has a feature that enables parsing of the date and time values that we will focus on in this section. Bash allows you to get the current date and time using the ‘date’ command. ‘S,’ ‘d’, ‘M,’ ‘m’, ‘Y,’ and ‘H’ are values used to analyze date and time. Create a file named ‘date_parse.sh’ and add a code that will detach month, year, day, hour, minutes, and the seconds’ values. #!/bin/bash Year=`date +%Y` Month=`date +%m` Day=`date +%d` Hour=`date +%H` Minute=`date +%M` Second=`date +%S` echo `date` echo "Current Date is: $Day-$Month-$Year" echo "Current Time is: $Hour:$Minute:$Second" Execute the file with the bash command. bash date_parse.sh Parse Current Date Illustration

29. The Wait command

Linux OS has a built-in command feature that awaits to complete any running process by using a peculiar id to finish that particular assigned task. Therefore, when there is no job id, the wait command will wait for all secondary cycles to complete before returning exiting. Create a file named ‘wait_example.sh’ and add the script below for execution. #!/bin/bash echo "Waiting command" & process_id=$! wait $process_id echo "Exited with status $?" Execute the file using the bash command. bash wait_example.sh The Wait command Illustration

30. The Sleep Command

The sleep command helps the user to pause an ongoing task for a specified period. It gives you the allowance of delaying or halting/pausing for hours, minutes, seconds, or days. For illustration purposes, create a file and name it ‘sleep_examples.sh’, thereafter run the script shown below. The example aims to delay the task for approximately 8 seconds after execution. #!/bin/bash echo “Please be patient for 8 seconds” sleep 8 echo “Completed” Execute the file using the bash command bash sleep_examples.sh The Sleep Command Illustration

31. The AND Operator

This operator allows the system to check if multiple conditions have been satisfied. This means that all conditions separated by the AND operator must be true for correct execution. Additionally, the ‘&&’ operator is used to denote ‘AND’. To ascertain this, check the example below. First, create a file called ‘And_operator.sh’ then execute it using bash command-line. #!/bin/bash echo -n "Input a Number:" read num if [[ ( $num -lt 20 ) && ( $num%2 -eq 0 ) ]]; then echo "It is an Even Number" else echo "It is an Odd Number" fi Execute the file using the bash command-line bash And_operator.sh The AND Operator Illustration

32. The OR Operator

This is a great bash scripting construct that aids in creating complex logic in scripts. This construct works slightly differently than the ‘AND’ operator because it either returns true whenever the operands outcome is true. On the other hand, the ‘or’ operator only returns false whenever both the operands are false. Check the sample below for more elaboration. To find out about this construct, create a file named ‘OR_operator.sh’ and complete its execution using the command line. #!/bin/bash echo -n "Enter any number:" read n if [[ ( $n -eq 5 || $n -eq 30 ) ]] then echo "You won" else echo "You lost!" fi Command-line execution using bash bash OR_operator.sh The OR Operator Illustration

33. The switch construct

The Switch construct is applicable in situations where nested conditions are needed. The example below gives a detailed outline. Create a file named ‘switch_construct.sh’. Then execute the file using the bash command-line #!/bin/bash echo -n "Input a number: " read number case $number in 50) echo "Fifty!!" ;; 100) echo "Double fifty!!" ;; *) echo "Neither 100 nor 200" ;; esac Execute the file with the bash command-line bash switch_construct.sh The switch construct Illustration

34. Concatenating strings

With its advanced comfort-ability, bash allows easy implementation of concatenating string. This has been simplified by the example below. For demonstration purposes, create a file named ‘concatenating_strings.sh’ and run the file in the bash command line. You will get an output similar to the one below. #!/bin/bash string1="FossLinux" string2="Blogsite" string=$string1$string2 echo "$string is a great resource for Linux users to find relevant tutorials." Execute the file with the bash command bash concatenating_strings Concatenating strings Illustration

35. Slicing strings

The slicing string refers to the reduction of parts of a string. Unlike many programming languages that offer truncation of strings, bash doesn’t provide this feature. Below is an example to make you get a glimpse of what we are talking about. First, create a file named ‘slicing_strings.sh’. Thereafter, execute the created slicing file using the bash command line. #!/bin/bash Str="Study smart commands with fosslinux" subStr=${Str:0:20} echo $subStr The output in the script above should be ‘Study Smart commands.’ The expansion in parameter takes the formula {VAR_NAME: S: L). in this formula, S shows the starting position, whereas L denotes the length. bash slicing_strings.sh slicing strings Illustration

Conclusion

The article has covered 35 bash script examples giving the user a diverse learning range. If you have been looking for an all-around article with bash script examples, this should be your ultimate choice.

35 Bash Script Examples

Simple Backup bash shell script
Variables in Bash scripts
Global vs. Local variables
Passing arguments to the bash script
Executing shell commands with bash
Reading User Input
Bash Trap Command
Arrays
Declare simple bash array
Read file into bash array
Bash if / else / fi statements
Nested if/else
Bash Comparisons
Arithmetic Comparisons
String Comparisons
Bash File Testing
Loops
Bash for loop
Bash while loop
Bash until loop
Control bash loop with input
Bash Functions
Bash Select
Case statement conditional
Bash quotes and quotations
Escaping Meta characters
Single quotes
Double quotes
Bash quoting with ANSI-C style
Arithmetic Operations
Bash Addition Calculator Example
Bash Arithmetics
Round floating point number
Bash floating point calculations
Redirections
STDOUT from bash script to STDERR
STDERR from bash script to STDOUT
stdout to screen
stdout to file
stderr to file
stdout to stderr
stderr to stdout
stderr and stdout to file
Closing Thoughts


First you need to find out where is your Bash interpreter located. Enter the following into your command line: $ which bash /bin/bash This command reveals that the Bash shell is stored in /bin/bash. This will come into play momentarily. The next thing you need to do is open our favorite text editor and create a file called hello_world.sh. We will use nano for this step. $ nano hello_world.sh Copy and paste the following lines into the new file: #!/bin/bash # declare STRING variable STRING="Hello World" # print variable on a screen echo $STRING NOTE: Every bash shell script in this tutorial starts with a shebang: #! which is not read as a comment. First line is also a place where you put your interpreter which is in this case: /bin/bash. Navigate to the directory where your hello_world.sh script is located and make the file executable: $ chmod +x hello_world.sh Now you are ready to execute your first bash script: $ ./hello_world.sh The output you receive should simply be: Hello World

Simple Backup bash shell script

When writing a Bash script, you are basically putting into it the same commands that you could execute directly on the command line. A perfect example of this is the following script: #!/bin/bash tar -czf myhome_directory.tar.gz /home/linuxconfig This will create a compressed tar file of the home directory for user linuxconfig. The tar command we use in the script could easily just be executed directly on the command line. So, what's the advantage of the script? Well, it allows us to quickly call this command without having to remember it or type it every time. We could also easily expand the script later on to be more complex.

Variables in Bash scripts

In this example we declare simple bash variable $STRING and print it on the screen (stdout) with echo command. #!/bin/bash STRING="HELLO WORLD!!!" echo $STRING The result when we execute the script: $ ./hello_world.sh HELLO WORLD!!! Circling back to our backup script example, let's use a variable to name our backup file and put a time stamp in the file name by using the date command. #!/bin/bash OF=myhome_directory_$(date +%Y%m%d).tar.gz tar -czf $OF /home/linuxconfig The result of executing the script: $ ./backup.sh $ ls myhome_directory_$(date +20220209).tar.gz Now, when we see the file, we can quickly determine that the backup was performed on February 9, 2022.

Global vs. Local variables

In Bash scripting, a global variable is a variable that can be used anywhere inside the script. A local variable will only be used within the function that it is declared in. Check out the example below where we declare both a global variable and local variable. We've made some comments in the script to make it a little easier to digest. #!/bin/bash # Define bash global variable # This variable is global and can be used anywhere in this bash script VAR="global variable" function bash { # Define bash local variable # This variable is local to bash function only local VAR="local variable" echo $VAR } echo $VAR bash # Note the bash global variable did not change # "local" is bash reserved word echo $VAR The result of executing this script: $ ./variables.sh global variable local variable global variable

Passing arguments to the bash script

When executing a Bash script, it is possible to pass arguments to it in your command. As you can see in the example below, there are multiple ways that a Bash script can interact with the arguments we provide. #!/bin/bash # use predefined variables to access passed arguments #echo arguments to the shell echo $1 $2 $3 ' -> echo $1 $2 $3' # We can also store arguments from bash command line in special array args=("$@") #echo arguments to the shell echo ${args[0]} ${args[1]} ${args[2]} ' -> args=("$@"); echo ${args[0]} ${args[1]} ${args[2]}' #use $@ to print out all arguments at once echo $@ ' -> echo $@' # use $# variable to print out # number of arguments passed to the bash script echo Number of arguments passed: $# ' -> echo Number of arguments passed: $#' Let's try executing this script and providing three arguments. $ ./arguments.sh Bash Scripting Tutorial The results when we execute this script: Bash Scripting Tutorial -> echo $1 $2 $3 Bash Scripting Tutorial -> args=("$@"); echo ${args[0]} ${args[1]} ${args[2]} Bash Scripting Tutorial -> echo $@ Number of arguments passed: 3 -> echo Number of arguments passed: $#

Executing shell commands with bash

The best way to execute a separate shell command inside of a Bash script is by creating a new subshell through the $( ) syntax. Check the example below where we echo the result of running the uname -o command. #!/bin/bash # use a subshell $() to execute shell command echo $(uname -o) # executing bash command without subshell echo uname -o Notice that in the final line of our script, we do not execute the uname command within a subshell, therefore the text is taken literally and output as such. $ uname -o GNU/LINUX $ ./subshell.sh GNU/LINUX uname -o

Reading User Input

We can use the read command to read input from the user. This allows a user to interact with a Bash script and help dictate the way it proceeds. Here's an example: #!/bin/bash echo -e "Hi, please type the word: \c " read word echo "The word you entered is: $word" echo -e "Can you please enter two words? " read word1 word2 echo "Here is your input: \"$word1\" \"$word2\"" echo -e "How do you feel about bash scripting? " # read command now stores a reply into the default build-in variable $REPLY read echo "You said $REPLY, I'm glad to hear that! " echo -e "What are your favorite colours ? " # -a makes read command to read into an array read -a colours echo "My favorite colours are also ${colours[0]}, ${colours[1]} and ${colours[2]}:-)" Our Bash script asks multiple questions and then is able to repeat the information back to us through variables and arrays: $ ./read.sh Hi, please type the word: Linuxconfig.org The word you entered is: Linuxconfig.org Can you please enter two words? Debian Linux Here is your input: "Debian" "Linux" How do you feel about bash scripting? good You said good, I'm glad to hear that! What are your favorite colours ? blue green black My favorite colours are also blue, green and black:-)

Bash Trap Command

The trap command can be used in Bash scripts to catch signals sent to the script and then execute a subroutine when they occur. The script below will detect a Ctrl + C interrupt. #!/bin/bash # bash trap command trap bashtrap INT # bash clear screen command clear; # bash trap function is executed when CTRL-C is pressed: # bash prints message => Executing bash trap subrutine ! bashtrap() { echo "CTRL+C Detected !...executing bash trap !" } # for loop from 1/10 to 10/10 for a in `seq 1 10`; do echo "$a/10 to Exit." sleep 1; done echo "Exit Bash Trap Example!!!" In the output below you can see that we try to Ctrl + C two times but the script continues to execute. $ ./trap.sh 1/10 to Exit. 2/10 to Exit. ^CCTRL+C Detected !...executing bash trap ! 3/10 to Exit. 4/10 to Exit. 5/10 to Exit. 6/10 to Exit. 7/10 to Exit. ^CCTRL+C Detected !...executing bash trap ! 8/10 to Exit. 9/10 to Exit. 10/10 to Exit. Exit Bash Trap Example!!!

Arrays

Bash is capable of storing values in arrays. Check the sections below for two different examples.

Declare simple bash array

This example declares an array with four elements. #!/bin/bash #Declare array with 4 elements ARRAY=( 'Debian Linux' 'Redhat Linux' Ubuntu Linux ) # get number of elements in the array ELEMENTS=${#ARRAY[@]} # echo each element in array # for loop for (( i=0;i<$ELEMENTS;i++)); do echo ${ARRAY[${i}]} done Executing the script will output the elements of our array: $ ./arrays.sh Debian Linux Redhat Linux Ubuntu Linux

Read file into bash array

Rather than filling out all of the elements of our array in the Bash script itself, we can program our script to read input and put it into an array. #!/bin/bash # Declare array declare -a ARRAY # Link filedescriptor 10 with stdin exec 10<&0 # stdin replaced with a file supplied as a first argument exec < $1 let count=0 while read LINE; do ARRAY[$count]=$LINE ((count++)) done echo Number of elements: ${#ARRAY[@]} # echo array's content echo ${ARRAY[@]} # restore stdin from filedescriptor 10 # and close filedescriptor 10 exec 0<&10 10<&- Now let's execute the script and store four elements in the array by using a file's contents for input. $ cat bash.txt Bash Scripting Tutorial Guide $ ./bash-script.sh bash.txt Number of elements: 4 Bash Scripting Tutorial Guide

Bash if / else / fi statements

Here is a simple if statement that check to see if a directory exists or not. Depending on the result, it will do one of two things. Please note the spacing inside the [ and ] brackets! Without the spaces, it won’t work! #!/bin/bash directory="./BashScripting" # bash check if directory exists if [ -d $directory ]; then echo "Directory exists" else echo "Directory does not exist" fi The output: $ ./bash_if_else.sh Directory does not exist $ mkdir BashScripting $ ./bash_if_else.sh Directory exists

Nested if/else

It is possible to place an if statement inside yet another if statement. This is called nesting. Scripts can get a bit complex depending on how many if statements deep it is. #!/bin/bash # Declare variable choice and assign value 4 choice=4 # Print to stdout echo "1. Bash" echo "2. Scripting" echo "3. Tutorial" echo -n "Please choose a word [1,2 or 3]? " # Loop while the variable choice is equal 4 # bash while loop while [ $choice -eq 4 ]; do # read user input read choice # bash nested if/else if [ $choice -eq 1 ] ; then echo "You have chosen word: Bash" else if [ $choice -eq 2 ] ; then echo "You have chosen word: Scripting" else if [ $choice -eq 3 ] ; then echo "You have chosen word: Tutorial" else echo "Please make a choice between 1-3 !" echo "1. Bash" echo "2. Scripting" echo "3. Tutorial" echo -n "Please choose a word [1,2 or 3]? " choice=4 fi fi fi done Output from the script: $ ./nested_if_else.sh 1. Bash 2. Scripting 3. Tutorial Please choose a word [1,2 or 3]? 5 Please make a choice between 1-3 ! 1. Bash 2. Scripting 3. Tutorial Please choose a word [1,2 or 3]? 2 You have chosen word: Scripting

Bash Comparisons

Bash can compare two or more values, either integers or strings, to determine if they are equal to each other, or one is greater than the other, etc.

Arithmetic Comparisons

-lt <
-gt >
-le <=
-ge >=
-eq ==
-ne !=
Now let's use these operators in some examples. #!/bin/bash # declare integers NUM1=2 NUM2=2 if [ $NUM1 -eq $NUM2 ]; then echo "Both values are equal" else echo "Values are NOT equal" fi The result: $ ./statement.sh Both values are equal Let's try changing one of the numbers. #!/bin/bash # declare integers NUM1=2 NUM2=1 if [ $NUM1 -eq $NUM2 ]; then echo "Both Values are equal" else echo "Values are NOT equal" fi The result: $ ./statement.sh Values are NOT equal Let's add a little more complexity by including an elif statement and determing which number is larger. #!/bin/bash # declare integers NUM1=2 NUM2=1 if [ $NUM1 -eq $NUM2 ]; then echo "Both values are equal" elif [ $NUM1 -gt $NUM2 ]; then echo "NUM1 is greater than NUM2" else echo "NUM2 is greater than NUM1" fi The result: $ ./statement.sh NUM1 is greater than NUM2

String Comparisons

= equal
!= not equal
< less then
> greater then
-n s1 string s1 is not empty
-z s1 string s1 is empty
Let's try comparing two strings to see if they are equal. #!/bin/bash #Declare string S1 S1="Bash" #Declare string S2 S2="Scripting" if [ $S1 = $S2 ]; then echo "Both Strings are equal" else echo "Strings are NOT equal" fi The result: $ ./statement.sh Strings are NOT equal And again with both string matching. #!/bin/bash #Declare string S1 S1="Bash" #Declare string S2 S2="Bash" if [ $S1 = $S2 ]; then echo "Both Strings are equal" else echo "Strings are NOT equal" fi The result: $ ./statement.sh Both Strings are equal

Bash File Testing

In Bash, we can test to see different characteristics about a file or directory. See the table below for a full list.
-b filename Block special file
-c filename Special character file
-d directoryname Check for directory existence
-e filename Check for file existence
-f filename Check for regular file existence not a directory
-G filename Check if file exists and is owned by effective group ID.
-g filename true if file exists and is set-group-id.
-k filename Sticky bit
-L filename Symbolic link
-O filename True if file exists and is owned by the effective user id.
-r filename Check if file is a readable
-S filename Check if file is socket
-s filename Check if file is nonzero size
-u filename Check if file set-ser-id bit is set
-w filename Check if file is writable
-x filename Check if file is executable
The following script will check to see if a file exists or not. #!/bin/bash file="./file" if [ -e $file ]; then echo "File exists" else echo "File does not exist" fi The result: $ ./filetesting.sh File does not exist $ touch file $ ./filetesting.sh File exists Similarly for example we can use while loop to check if file does not exist. This script will sleep until file does exist. Note bash negator ! which negates the -e option. #!/bin/bash while [ ! -e myfile ]; do # Sleep until file does exists/is created sleep 1 done

Loops

There are multiple types of loops that can be used in Bash, including for, while, and until. See some of the examples below to learn how to use.

Bash for loop

This script will list every file or directory it finds inside the /var/ directory. #!/bin/bash # bash for loop for f in $( ls /var/ ); do echo $f done A for loop can also be run directly from the command line, no need for a script: $ for f in $( ls /var/ ); do echo $f; done The result: $ ./for_loop.sh backups cache crash lib local lock log mail metrics opt run snap spool tmp

Bash while loop

This while loop will continue to loop until our variable reaches a value of 0 or less. #!/bin/bash COUNT=6 # bash while loop while [ $COUNT -gt 0 ]; do echo Value of count is: $COUNT let COUNT=COUNT-1 done The result: $ ./while_loop.sh Value of count is: 6 Value of count is: 5 Value of count is: 4 Value of count is: 3 Value of count is: 2 Value of count is: 1

Bash until loop

An until loop works similarly to while. #!/bin/bash COUNT=0 # bash until loop until [ $COUNT -gt 5 ]; do echo Value of count is: $COUNT let COUNT=COUNT+1 done The result: $ ./until_loop.sh Value of count is: 0 Value of count is: 1 Value of count is: 2 Value of count is: 3 Value of count is: 4 Value of count is: 5

Control bash loop with input

Here is a example of while loop controlled by standard input. Until the redirection chain from STDOUT to STDIN to the read command exists the while loop continues. #!/bin/bash # This bash script will locate and replace spaces # in the filenames DIR="." # Controlling a loop with bash read command by redirecting STDOUT as # a STDIN to while loop # find will not truncate filenames containing spaces find $DIR -type f | while read file; do # using POSIX class [:space:] to find space in the filename if [[ "$file" = *[[:space:]]* ]]; then # substitute space with "_" character and consequently rename the file mv "$file" `echo $file | tr ' ' '_'` fi; # end of while loop done

Bash Functions

This example shows how to declare a function and call back to it later in the script. !/bin/bash # BASH FUNCTIONS CAN BE DECLARED IN ANY ORDER function function_B { echo Function B. } function function_A { echo $1 } function function_D { echo Function D. } function function_C { echo $1 } # FUNCTION CALLS # Pass parameter to function A function_A "Function A." function_B # Pass parameter to function C function_C "Function C." function_D The result: $ ./functions.sh Function A. Function B. Function C. Function D.

Bash Select

The select command allows us to prompt the user to make a selection. #!/bin/bash PS3='Choose one word: ' # bash select select word in "linux" "bash" "scripting" "tutorial" do echo "The word you have selected is: $word" # Break, otherwise endless loop break done exit 0 The result: $ ./select.sh 1) linux 2) bash 3) scripting 4) tutorial Choose one word: 2 The word you have selected is: bash

Case statement conditional

The case statement makes it easy to have many different possibilities, whereas an if statement can get lengthy very quickly if you have more than a few possibilities to account for. #!/bin/bash echo "What is your preferred programming / scripting language" echo "1) bash" echo "2) perl" echo "3) phyton" echo "4) c++" echo "5) I do not know !" read case; #simple case bash structure # note in this case $case is variable and does not have to # be named case this is just an example case $case in 1) echo "You selected bash";; 2) echo "You selected perl";; 3) echo "You selected phyton";; 4) echo "You selected c++";; 5) exit esac The result: $ ./case.sh What is your preferred programming / scripting language 1) bash 2) perl 3) phyton 4) c++ 5) I do not know ! 3 You selected phyton

Bash quotes and quotations

Quotations and quotes are important part of bash and bash scripting. Here are some bash quotes and quotations basics.

Escaping Meta characters

Before we start with quotes and quotations we should know something about escaping meta characters. Escaping will suppress a special meaning of meta characters and therefore meta characters will be read by bash literally. To do this we need to use backslash \ character. Example: #!/bin/bash #Declare bash string variable BASH_VAR="Bash Script" # echo variable BASH_VAR echo $BASH_VAR #when meta character such us "$" is escaped with "\" it will be read literally echo \$BASH_VAR # backslash has also special meaning and it can be suppressed with yet another "\" echo "\\" Here's what it looks like when we execute the script: $ ./escape_meta.sh Bash Script $BASH_VAR \

Single quotes

Single quotes in bash will suppress special meaning of every meta characters. Therefore meta characters will be read literally. It is not possible to use another single quote within two single quotes not even if the single quote is escaped by backslash. #!/bin/bash # Declare bash string variable BASH_VAR="Bash Script" # echo variable BASH_VAR echo $BASH_VAR # meta characters special meaning in bash is suppressed when using single quotes echo '$BASH_VAR "$BASH_VAR"' The result: $ ./single_quotes.sh Bash Script $BASH_VAR "$BASH_VAR"

Double quotes

Double quotes in bash will suppress special meaning of every meta characters except $, \ and `. Any other meta characters will be read literally. It is also possible to use single quote within double quotes. If we need to use double quotes within double quotes bash can read them literally when escaping them with \. Example: #!/bin/bash #Declare bash string variable BASH_VAR="Bash Script" # echo variable BASH_VAR echo $BASH_VAR # meta characters and its special meaning in bash is # suppressed when using double quotes except "$", "\" and "`" echo "It's $BASH_VAR and \"$BASH_VAR\" using backticks: `date`" The result: $ ./double_quotes.sh Bash Script It's Bash Script and "Bash Script" using backticks: Thu 10 Feb 2022 10:24:15 PM EST

Bash quoting with ANSI-C style

There is also another type of quoting and that is ANSI-C. In this type of quoting characters escaped with \ will gain special meaning according to the ANSI-C standard.
\a alert (bell) \b backspace
\e an escape character \f form feed
\n newline \r carriage return
\t horizontal tab \v vertical tab
\\ backslash \` single quote
\nnn octal value of characters ( see [http://www.asciitable.com/ ASCII table] ) \xnn hexadecimal value of characters ( see [http://www.asciitable.com/ ASCII table] )
The syntax for ansi-c bash quoting is: $' ' . Here is an example: #!/bin/bash # as a example we have used \n as a new line, \x40 is hex value for @ # and \56 is octal value for . echo $'web: www.linuxconfig.org\nemail: web\x40linuxconfig\56org' The result: $ ./bash_ansi-c.sh web: www.linuxconfig.org email: web@linuxconfig.org

Arithmetic Operations

Bash can be used to perform calculations. Let's look at a few examples to see how it's done.

Bash Addition Calculator Example

#!/bin/bash let RESULT1=$1+$2 echo $1+$2=$RESULT1 ' -> # let RESULT1=$1+$2' declare -i RESULT2 RESULT2=$1+$2 echo $1+$2=$RESULT2 ' -> # declare -i RESULT2; RESULT2=$1+$2' echo $1+$2=$(($1 + $2)) ' -> # $(($1 + $2))' The result: $ ./bash_addition_calc.sh 88 12 88+12=100 -> # let RESULT1=$1+$2 88+12=100 -> # declare -i RESULT2; RESULT2=$1+$2 88+12=100 -> # $(($1 + $2))

Bash Arithmetics

Let's see how to do some basic Bash aritmetics such as addition, subtraction, multiplication, division, etc. #!/bin/bash echo '### let ###' # bash addition let ADDITION=3+5 echo "3 + 5 =" $ADDITION # bash subtraction let SUBTRACTION=7-8 echo "7 - 8 =" $SUBTRACTION # bash multiplication let MULTIPLICATION=5*8 echo "5 * 8 =" $MULTIPLICATION # bash division let DIVISION=4/2 echo "4 / 2 =" $DIVISION # bash modulus let MODULUS=9%4 echo "9 % 4 =" $MODULUS # bash power of two let POWEROFTWO=2**2 echo "2 ^ 2 =" $POWEROFTWO echo '### Bash Arithmetic Expansion ###' # There are two formats for arithmetic expansion: $[ expression ] # and $(( expression #)) its your choice which you use echo 4 + 5 = $((4 + 5)) echo 7 - 7 = $[ 7 - 7 ] echo 4 x 6 = $((3 * 2)) echo 6 / 3 = $((6 / 3)) echo 8 % 7 = $((8 % 7)) echo 2 ^ 8 = $[ 2 ** 8 ] echo '### Declare ###' echo -e "Please enter two numbers \c" # read user input read num1 num2 declare -i result result=$num1+$num2 echo "Result is:$result " # bash convert binary number 10001 result=2#10001 echo $result # bash convert octal number 16 result=8#16 echo $result # bash convert hex number 0xE6A result=16#E6A echo $result The result: $ ./arithmetic_operations.sh ### let ### 3 + 5 = 8 7 - 8 = -1 5 * 8 = 40 4 / 2 = 2 9 % 4 = 1 2 ^ 2 = 4 ### Bash Arithmetic Expansion ### 4 + 5 = 9 7 - 7 = 0 4 x 6 = 6 6 / 3 = 2 8 % 7 = 1 2 ^ 8 = 256 ### Declare ### Please enter two numbers 23 45 Result is:68 17 14 3690

Round floating point number

Here is how to use rounding in Bash calculations. #!/bin/bash # get floating point number floating_point_number=3.3446 echo $floating_point_number # round floating point number with bash for bash_rounded_number in $(printf %.0f $floating_point_number); do echo "Rounded number with bash:" $bash_rounded_number done The result: $ ./round.sh 3.3446 Rounded number with bash: 3

Bash floating point calculations

Using the bc bash calculator to perform floating point calculations. #!/bin/bash # Simple linux bash calculator echo "Enter input:" read userinput echo "Result with 2 digits after decimal point:" echo "scale=2; ${userinput}" | bc echo "Result with 10 digits after decimal point:" echo "scale=10; ${userinput}" | bc echo "Result as rounded integer:" echo $userinput | bc The result: $ ./simple_bash_calc.sh Enter input: 10/3.4 Result with 2 digits after decimal point: 2.94 Result with 10 digits after decimal point: 2.9411764705 Result as rounded integer: 2

Redirections

In the following examples, we will show how to redirect standard error and standard output.

STDOUT from bash script to STDERR

#!/bin/bash echo "Redirect this STDOUT to STDERR" 1>&2 To prove that STDOUT is redirected to STDERR we can redirect script’s output to file: $ ./redirecting.sh Redirect this STDOUT to STDERR $ ./redirecting.sh > STDOUT.txt $ cat STDOUT.txt $ $ ./redirecting.sh 2> STDERR.txt $ cat STDERR.txt Redirect this STDOUT to STDERR

STDERR from bash script to STDOUT

#!/bin/bash cat $1 2>&1 To prove that STDERR is redirected to STDOUT we can redirect script’s output to file: $ ./redirecting.sh /etc/shadow cat: /etc/shadow: Permission denied $ ./redirecting.sh /etc/shadow > STDOUT.txt $ cat STDOUT.txt cat: /etc/shadow: Permission denied $ ./redirecting.sh /etc/shadow 2> STDERR.txt cat: /etc/shadow: Permission denied $ cat STDERR.txt $

stdout to screen

The simple way to redirect a standard output (stdout) is to simply use any command, because by default stdout is automatically redirected to screen. First create a file file1: $ touch file1 $ ls file1 file1 As you can see from the example above execution of ls command produces STDOUT which by default is redirected to screen.

stdout to file

To override the default behavior of STDOUT we can use > to redirect this output to file: $ ls file1 > STDOUT $ cat STDOUT file1

stderr to file

By default STDERR is displayed on the screen: $ ls file1 STDOUT $ ls file2 ls: cannot access file2: No such file or directory In the following example we will redirect the standard error (stderr) to a file and stdout to a screen as default. Please note that STDOUT is displayed on the screen, however STDERR is redirected to a file called STDERR: $ ls file1 STDOUT $ ls file1 file2 2> STDERR file1 $ cat STDERR ls: cannot access file2: No such file or directory

stdout to stderr

It is also possible to redirect STDOUT and STDERR to the same file. In the next example we will redirect STDOUT to the same descriptor as STDERR. Both STDOUT and STDERR will be redirected to file “STDERR_STDOUT”. $ ls file1 STDERR STDOUT $ ls file1 file2 2> STDERR_STDOUT 1>&2 $ cat STDERR_STDOUT ls: cannot access file2: No such file or directory file1 File STDERR_STDOUT now contains STDOUT and STDERR.

stderr to stdout

The above example can be reversed by redirecting STDERR to the same descriptor as SDTOUT: $ ls file1 STDERR STDOUT $ ls file1 file2 > STDERR_STDOUT 2>&1 $ cat STDERR_STDOUT ls: cannot access file2: No such file or directory file1

stderr and stdout to file

Previous two examples redirected both STDOUT and STDERR to a file. Another way to achieve the same effect is illustrated below: $ ls file1 STDERR STDOUT $ ls file1 file2 &> STDERR_STDOUT $ cat STDERR_STDOUT ls: cannot access file2: No such file or directory file1 or ls file1 file2 >& STDERR_STDOUT $ cat STDERR_STDOUT ls: cannot access file2: No such file or directory file1

Closing Thoughts

In this Bash scripting tutorial, we learned how to get started with Bash scripting by learning all the basics of the most common aspects, such as loops, arithmetic, comparisons, etc. This guide has served as an introduction to Bash scripting concepts, and given you some insight into how the Bash shell works. By adapting our examples for your own needs and expanding them as needed, you will be well on your way to mastering Bash scripting.

25 basic Ubuntu Commands

There are several releases of Ubuntu, such as stable release, Long Term Support (LTS), and unstable. The stable and unstable releases are launched every year in April and October, respectively, whereas the long-term support variant is released after two years and is available for the next five years. Ubuntu supports both Command Line Interface (CLI) and Graphical User Interface (GUI) to perform various tasks on the OS. CLI is the basic way to interact with systems hardware (processor/memory); you can perform all the tasks that GUI can perform. In this article, we will demonstrate the use of 25 basic commands that provide ease to execute various tasks of Ubuntu using CLI.

Command: pwd

This command refers to the present working directory in which you are operating; in simpler words, in which your terminal is open. To check PWD, execute the pwd keyword in your terminal and hit enter; the command of PWD is written below along with the result of that command. $ pwd

Command: dir

The dir command is used to print (on the terminal) all the available directories in the present working directory: $ dir

Command: ls

This command is used to list down all the directories and files inside the present working directory (or you can give the path of a specific directory); the ls command can be executed as shown below: $ ls The ls command supports various flags, and each flag has some specific role in printing the directories or files of the current working directory. To print the detailed information of the files/directories; the “-al” flag is used with the “ls” command: $ ls -al The “-R” flag will print subdirectories of a directory as well: $ ls -R Moreover, to get the hidden files, “-a” flag is used: $ ls -a

Command: cd

One of the most used commands of Ubuntu; you can change the directories in the terminal using the “cd” command. For instance, the following command will change the pwd to desktop. $ cd Desktop There are multiple uses of this command: one can change the present directory to root directory or home directory using this command. When you open a fresh terminal, you are in the home directory. To change directory to root. For instance, we are in the Desktop directory and want to switch to the root directory: $ cd / To change the present directory to the home directory: $ cd

Command: touch

This Ubuntu command can be used to create a new file as well one can use it to change the timestamp of any file; the command given below will create a new text time in pwd: $ touch file1.txt If we execute a touch command to create a file, but the file is already created, then it would change the timestamp of that file to the current time; for instance, the command given below will change the timestamp of the file1.txt. you can check that the timestamp has been changed to the current time: $ touch file1.txt

Command: cat

This command is used to show the content of any file: For instance, the following command will display the content inside “file1.txt”: $ cat file1.txt Or you can use this command to save the content of multiples files to one file: $ cat file1.txt file2.txt > output.txt

Command: mkdir

The above-mentioned command will make a directory in your pwd; for example, the following command will make the directory “new” in pwd. $ mkdir new

Command: rm

This remove command is used to remove the specific file from a directory; For instance, below mentioned command would remove the “test.txt” file from the pwd: $ rm test.txt Or you can remove the empty directory, as the command given below will remove the “test” directory: $ rmdir test

Command: cp

The cp command will help you to copy any file or folder to any directory; To copy a file to directory1: $ cp file1.txt directory1 If you want to copy the complete folder, then; $ cp new -r directory1

Command: mv

You can use this command to move files around the computer, and you can also rename files or directories inside a specific directory: the command given below will move the “file2.txt” to “directory1”: $ mv file2.txt directory1 Moreover, the command given below will move the “test1” directory to “directory1”: $ mv test1 directory1

Command: head

This command helps you to get the first ten lines of a text file; for instance, the following command will help to get the first ten lines of the “file1.text” file: $ head file1.txt

Command: tail

The tail command is used to get the last ten lines of the text file; the command below will print the ten lines from the bottom of “file1.txt”: $ tail file1.txt

Command: uname

You can use the command to get the release number, version of Linux, and much more. The “-a” flag is used to get detailed information. $ uname -a

Command: wget

You can use the wget command to download the content from the internet; for instance, the following command will download VirtualBox. $ wget https://download.virtualbox.org/virtualbox/6.1.26/VirtualBox-6.1.26-145957-Win.exe

Command: apt-get or -apt

This is one of the most important and most used commands of Ubuntu that works with Ubuntu Advanced Packaging Tool (APT); you can use this “-apt-get” or “-apt” to install or remove packages, or you can perform other maintenance tasks. The “apt” requires sudo privileges to successfully execute the command. The syntax stated below will help you to install the required package: $ sudo apt install [packagename] For install to install vlc media player package use: $ sudo apt install vlc Or you can remove the package by executing the command given below: $ sudo apt remove [packagename] And to delete vlc media player package:

Command: history

The history command shows the list of commands (with numeric numbers) executed: $ history And you can execute any of the listed commands. For instance, if you want to execute the 2nd command (which is apt update command), then you have to write “!2” to get the result of that command: $ !2

Command: grep

With the help of grep, you can search for a pattern in which a specific word lies; for instance, the command given below will print all the lines that contain “20” from “file1.txt”: $ cat file1.txt | grep 20

Command: man

The man command will help you to get the complete user manual of any specific command; for instance, the following command will list down the detailed usage of the “cat” command: $ man cat

Command: ps

Using the -ps command, you will be able to get the list of processes. $ ps

Command: zip or unzip

To convert your files to zip archive; you can get help by using the “gzip” command; moreover, a zipped file can be unzipped using the “gunzip” command: $ gzip file1.txt You can unzip the “file1.txt” as shown below: $ gunzip file1.txt

Command: hostname

This command will print your hostname on the terminal: $ hostname

Command: ping

You can use the ping command to check the connectivity to your server; for example, the command below will ping to YouTube and also prints the response time: $ ping youtube.com

Command: w

This command will display the user details that are currently logged into the system: $ w

Command: useradd

Ubuntu supports multiuser access; if you want to add another user to your system, execute the following command to do so: $ sudo useradd MIKE Or you can delete the user also; $ sudo userdel MIKE

Command: passwd

With the help of the passwd command, you can change the password of your Ubuntu user: You must pass “username” to “passwd” to change the password of that; for example, the command given below will change the password of user “adnan”. $ passwd adnan

Basic Ubuntu Commands for Beginner:

1. sudo

sudo (SuperUser DO) Linux command allows you to run programs or other commands with administrative privileges, just like “Run as administrator” in Windows. This is useful when, for example, you need to modify files in a directory that your user wouldn’t normally have access to.

2. apt-get

apt-get is the one of the most important Ubuntu commands every beginner must know. It is used to install, update, upgrade and remove any package. apt-get basically works on a database of available packages. Here is the list of different apt-get commands:

1. sudo apt-get update

apt-get update with super user privileges is the first command you need to run in any Linux system after a fresh install. This command updates the database and let your system know if there are newer packages available or not.

2. sudo apt-get upgrade

After updating the package database, next step is to to upgrade the installed packages. For upgrading all the packages with available updates you can use this command. And if you like to upgrade a particular package, you should tweak the above command a little: sudo apt-get upgrade <package-name> Replace the <package-name> with your desired package.

3. sudo apt-get install

If you know the name of the package, then you can easily install a program using this command: sudo apt-get install <package-name> Replace the <package-name> with your desired package. If you are not sure about the package name, you can type a few letters and press tab and it will suggest all the packages available with those letters. Thanks for auto-completion feature.

4. sudo apt-get remove

When it comes to removing the installed program apt-get remove command suits your need. You only have to know the exact package name of the software you want to uninstall. If you don’t know the package name, use below ubuntu basic command to list all the packages installed on your system and then copy the package name from the list: dpkg --list Now run the apt-get remove command as sudo in order to remove the software: sudo apt-get remove <package-name> Replace the <package-name> with the one you copied from the dpkg list. apt-get remove command only removes the software from your system but not the configuration or data files of the package. These files help in keeping the same settings when you want to reinstall the same software.

5. sudo apt-get purge

apt-get purge command is used when you want to remove a software completely from your system with its configuration or data files so that no longer personalized settings will be available during reinstallation. Run the apt-get purge command as sudo in order to remove the software completely: sudo apt-get purge <package-name> Replace the <package-name> with the application that you want to remove or copied from the dpkg list.

6. sudo apt-get autoremove

apt-get autoremove command is used to remove any unnecessary packages. Unnecessary means, whenever you install an application, the system will also install the software that this application depends on. It is common in Ubuntu that applications share the same libraries. When you remove the application the dependency will stay on your system. So run apt-get autoremove as sudo after uninstalling a package to remove unwanted software dependencies. So apt-get autoremove will remove those dependencies that were installed with applications and that are no longer used by anything else on the system.

3. ls

ls (list) command lists all files and folders in your current working directory. You can also specify paths to other directories if you want to view their contents.

4. cd

cd (change director”) Linux command also known as chdir used to change the current working directory. It’s one of the most used basic Ubuntu commands. Using this command is easy, just type cd followed by the the folder name. You can use full paths to folders or simply the name of a folder within the directory you are currently working. Some common uses are: Here are some examples to how to use cd command in Ubuntu: Example 1: cd home – open home folder in current directory. Example 2: cd Linux\ Drive – open Linux Drive named folder in directory. Here you can see I use backslash because the folder name has spaces so for each space you use “backslash+space”. Like, if your folder name is “am a programmer” then the cd command will be, “cd am\ a\ programmer”.

5. pwd

pwd (print working directory) Ubuntu command displays the full pathname of the current working directory.

6. cp

cp (copy) Linux command allows you to copy a file. You should specify both the file you want to be copied and the location you want it copied to – for example, cp xyz /home/myfiles would copy the file “xyz” to the directory “/home/myfiles.

7. mv

mv (move) command allows you to move files. You can also rename files by moving them to the directory they are currently in, but under a new name. The usage is the same as cp – for example mv xyz /home/myfiles would move the file “xyz” to the directory “/home/myfiles.

8. rm

rm (remove) command removes the specified file.

9. mkdir

mkdir (make directory) command allows you to create a new directory. You can specify where you want the directory created – if you do not do so, it will be created in your current working directory.

10. history

history command displays all of your previous commands up to the history limit.

11. df

df (display filesystem) command displays information about the disk space usage of all mounted filesystems.

12. du

du (directory usage) command displays the size of a directory and all of its subdirectories.

13. free

free – Displays the amount of free space available on the system.

14. uname -a

uname -a – Provides a wide range of basic information about the system.

15. top

top – Displays the processes using the most system resources at any given time. “q” can be used to exit.

16. man

man command displays a “manual page”. Manual pages are usually very detailed, and it’s recommended that you read the man pages for any command you are unfamiliar with. Some uses are :

17. info

Similar to man, but often provides more detailed or precise information.

18. <command name> -h or <command name> –help

This command is a third alternative to get help. While not as detailed as the info or man pages, this will provide a quick overview of the command and its uses. For example: man -h or man -help

19. passwd

passwd Ubuntu basic command is used to change user password using Terminal. What you have to do is run the below command, where is the username whose password has to change: passwd <user>

20. whatis

whatis command shows a brief description of what is the functionality of specific built-in Linux command. whatis <command> Some examples are: Above commands will display the purpose of cd, man and help commands.

Ubuntu Terminal Shortcuts:

To further ease up your skill, these Ubuntu Terminal keyboard shortcuts would help.
Ubuntu Terminal ShortcutsFunction
Ctrl + Shift + TOpen new tab on current terminal
Ctrl + Shift + WClose the current tab
Ctrl + AMove cursor to beginning of line
Ctrl + EMove cursor to end of line
Ctrl + UClears the entire current line
Ctrl + KClears the command from the cursor right
Ctrl + WDelete the word before the cursor
Ctrl + RAllows you to search your history for commands matching what you have typed
Ctrl + CKill the current process
Ctrl + ZSuspend the current process by sending the signal SIGSTOP
Ctrl + LClears the terminal output
Alt + FMove forward one word
Alt + BMove backward one word
Ctrl + Shift + CCopy the highlighted command to the clipboard
Ctrl + Shift + V or Shift + InsertPaste the contents of the clipboard
Up/Down Arrow keysTo scroll through your command history, allowing you to quickly execute the same command multiple times
TABUsed to complete the command you are typing. If more than one command is possible, you can press it multiple times to scroll through the possible completions. If a very wide number of commands are possible, it can output a list of all possible completions.

Troubleshooting in Windows Terminal

Opening the settings does nothing (or opens an unexpected application)

If you click on the "settings" button in the dropdown, the Terminal will attempt to open the settings file, settings.json. This will cause the OS to try and launch your configured .json file editor. This might be Visual Studio, or Notepad, or some other completely unexpected application. If there isn't a configured .json editor on your machine, then the OS will eventually show you the "How do you want to open this file" dialog. Tip You can also use the settings UI to configure your settings if you are using Windows Terminal Preview. You can learn how to open the settings UI on the Actions page.

Set your WSL distribution to start in the home ~ directory when launched in older versions of Windows Terminal

By default, the startingDirectory of a profile is %USERPROFILE% (C:\Users\<YourUsername>). This is a Windows path. For WSL distributions running a new version of Windows Terminal, the file systems can enter ~ to set this home path. In older versions of Windows Terminal, you can use /home/<Your Ubuntu Username> to directly refer to your home folder. For example, the following setting will launch the "Ubuntu-20.04" distribution in its home file path: { "name": "Ubuntu-20.04", "commandline" : "wsl -d Ubuntu-20.04", "startingDirectory" : "/home/<Your Ubuntu Username>" } If you are using a very early version of Windows Terminal, WSL may require using the \\wsl$\ prefix when referring to a distribution's home path for the startingDirectory setting. For example, the following setting will launch the "Ubuntu-18.04" distribution in its home file path: { "name": "Ubuntu-18.04", "commandline" : "wsl -d Ubuntu-18.04", "startingDirectory" : "//wsl$/Ubuntu-18.04/home/<Your Ubuntu Username>" } Important On newer versions of Windows, startingDirectory can accept Linux-style paths.

Setting the tab title

To have the shell automatically set your tab title, visit the set the tab title tutorial. If you want to set your own tab title, open the settings.json file and follow these steps: In the profile for the command line of your choice, add "suppressApplicationTitle": true to suppress any title change events that get sent from the shell. Adding only this setting to your profile will set the tab title to the name of your profile. If you want a custom tab title that is not the name of your profile, add "tabTitle": "TITLE". Replacing "TITLE" with your preferred tab title.

Command line arguments in PowerShell

Visit the Command line arguments page to learn how command-line arguments operate in PowerShell.

Command line arguments in WSL

Visit the Command line arguments page to learn how command-line arguments operate in WSL.

Problem setting startingDirectory

If the startingDirectory is being ignored in your profile, first check to make sure the syntax is correct in your settings.json file. To help you check this syntax, "$schema": "https://aka.ms/terminal-profiles-schema" is automatically injected. Some applications, like Visual Studio Code, can use that injected schema to validate your json file as you make edits. If your settings are correct, you may be running a startup script that sets the starting directory of your terminal separately. For example, PowerShell has its own separate concept of profiles. If you are changing your starting directory there, it will take precedence over the setting defined in Windows Terminal. Alternatively, if you are running a script using the commandline profile setting, it may be that you are setting the location there. Similar to PowerShell profiles, your commands there take precedence over the startingDirectory profile setting. The purpose of startingDirectory is to launch a new Windows Terminal instance in the given directory. If the terminal runs any code that changes its directory, that may be a good place to take a look.

Ctrl+= does not increase the font size

If you are using a German keyboard layout, you may run into this problem. ctrl+= gets deserialized as ctrl+shift+0 if your main keyboard layout is set to German. This is the correct mapping for German keyboards. More importantly, the app never receives the ctrl+shift+0 keystroke. This is because ctrl+shift+0 is reserved by Windows if you have multiple keyboard layouts active. If you would like to disable this feature in order for Ctrl+= to work properly, follow the instructions for "Change Hotkeys to Switch Keyboard Layout in Windows 10" in this blog post. Change the 'Switch Keyboard Layout' option to 'Not Assigned' (or off of ctrl+shift), then select OK and then Apply. ctrl+shift+0 should now work as a key binding and is passed through to the terminal. On the other hand, if you do use this hotkey feature for multiple input languages, you can configure your own custom key binding in your settings.json file.

The text is blurry

Some display drivers and hardware combinations do not handle scroll and/or dirty regions without blurring the data from the previous frame. To mitigate this problem, you can add a combination of these global rendering settings to reduce the strain placed on your hardware caused by the terminal text renderer.

My colors look strange! There are black bars on my screen!

Important This applies only to version 1.2+ of Windows Terminal. If you are seeing color issues in Windows Terminal 1.0 or 1.1, or issues that are not captured here, please file a bug. Windows Terminal 1.2 and beyond has an improved understanding of certain application color settings. Because of this improved understanding, we have been able to remove a number of compatibility blocks that resulted in a poor user experience. Unfortunately, there is a small number of applications that may experience issues. We will keep this troubleshooting item up-to-date with the list of known issues and their workarounds.

Black lines in PowerShell (5.1, 6.x, 7.0)

Terminal, when coupled with PowerShell's line editing library PSReadline, may draw black lines across the screen. These miscolored regions will extend across the screen beyond your prompt wherever there are command parameters, strings or operators. PSReadline version 2.0.3 has been released and contains a fix for this issue. If you are using the prerelease version of PSReadline, note that a fix is not yet available. To update to the newest version of PSReadline, please run the following command: Update-Module PSReadline

Why are my emojis not appearing as icons in the jumplist?

Only images linked from a file location can be rendered as profile icons in the jumplist. Emojis are not supported for jumplist icons.

Technical Notes

Applications that use the GetConsoleScreenBufferInfo family of APIs to retrieve the active console colors in Win32 format and then attempt to transform them into cross-platform VT sequences (for example, by transforming BACKGROUND_RED to \x1b[41m) may interfere with Terminal's ability to detect what background color the application is attempting to use. Application developers are encouraged to choose either Windows API functions or VT sequences for adjusting colors and not attempt to mix them.

Keyboard service warning

Starting in Windows Terminal 1.5, the Terminal will display a warning if the "Touch Keyboard and Handwriting Panel Service" is disabled. This service is needed by the operating system to properly route input events to the Terminal application (as well as many other applications on Windows). If you see this warning, you can follow these steps to re-enable the service: In the run dialog, run services.msc Find the "Touch Keyboard and Handwriting Panel Service" Open the "Properties" for this service Change the "startup type" to "Automatic" Hit "Ok", and restart the PC. After restarting the machine, the service should auto-start, and the dialog should no longer appear.

Why do I see blinking or flashing when using a git bash command line?

You may notice a blinking or flashing when using a git bash command line inside Windows Terminal. This behavior is actually by design. The Terminal is obeying what git bash is telling it to do (setting bell-style to visible, causing a flash to associate with the bell response), BUT we understand this may be distracting. To fix this, open the .inputrc file for your Git bash with a text editor. This file will likely be located in the path C:\Program Files\Git\etc. To open with the Nano text editor: nano ~/.inputrc Change the default: # none, visible or audible set bell-style visible Set the bell-style to either none or audible to remove the visible flash: set bell-style none Press Ctrl + O and Ctrl + X to Save and Exit.

How do I reset my settings in Windows Terminal back to the default settings?

To reset your settings back to the original default settings, delete your settings.json file. This will cause Windows Terminal to regenerate a settings.json file with the original default settings. Important As of Windows Terminal version 1.10 or greater, you'll also need to delete the state.json file in the same directory as the settings.json file to fully reset the settings to the defaults.

Why is Acrylic opacity not making my Windows Terminal background transparent?

You can set the transparency of a terminal window with the useAcrylic property. There are a few reasons why your opacity setting may not be working for Acrylic, including: